内容摘要
(1)在Spring的IOC容器里配置bean
实例:
<!--
配置bean
class:bean的全类名 ,通过反射的方式在ioc容器里创建bean。要求bean里必须有无参数的构造器
id: 唯一标识
-->
<bean name="helloworld" class="jjh.test.HelloWorld">
<property name="name" value="jjh"></property>
</bean>
(2)Spring容器
(3)ApplicationContext
①利用id获取IOC的bean与利用类信息获取bean
区别:利用id获取可以是任意个,用类信息则只能创建一个bean
实例:
// 1、创建Spring的IOC容器的对象
// ApplicationContext代表IOC容器
// ClassPathXmlApplicationContext:是ApplicationContext接口的实现类。该实现类从类路径下加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2、从IOC的容器中获取Bean的实例
//利用id定位到IOC容器中的Bean
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloworld2");
//利用类型返回IOC容器中的bean,要求IOC容器中只有一个该类型的bean
HelloWorld helloWorld2 = ctx.getBean(HelloWorld.class);
// 3、调用hello方法
helloWorld.sayHello();
helloWorld2.sayHello();
我在applicationContext.xml里创建了两个bean,class都为一个类,
在main(函数入口)里创建了一个靠id获取bean的对象和一个靠类获取bean的对象的实例
结果抛出异常
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [jjh.test.HelloWorld] is defined: expected single matching bean but found 2: helloworld,helloworld2
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:365)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:975)
at jjh.test.Main.main(Main.java:19)
NoUniqueBeanDefinitionException,系统启动出错,利用类信息调用bean时bean不唯一,IOC容器不知道选择哪个bean给组件。
(4)依赖注入的方式
属性注入和构造器注入都可以注入值
区别:属性注入在你执行方法是注入。构造器注入在你创建ApplicationContext实例时注入。
书写形式如下
需要注意的是构造器的index代表参数位置,index=0代表第0个参数,依次推列。如果不加index按照默认顺序配置