版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaizuidebanli/article/details/83099824
一、Spring配置bean
二、在 Spring 的 IOC 容器里配置 Bean
<!--
通过全类名的方式配置bean
id:名称,唯一标志
class: bean的全类名,通过反射的方式在IOC容器中创建Bean, 因此要求Bean中必须有无参构造器。
-->
<bean id="helloWorld" class="atguigu.Spring.HelloWorld">
<property name="user" value="kaizuidebanli"/>
</bean>
三、Spring 的容器
从IOC容器中获取Bean实例的方法
直接通过类性获取,代码实现如下所示:
@Test
public void testHello() throws Exception {
HelloWorld helloWorld = new HelloWorld();
// helloWorld.setUser("Tom");
// helloWorld.hello();
//1. 创建 Spring 的 IOC 容器
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//2. 从 IOC 容器中获取 bean 的实例
HelloWorld helloWorld = (HelloWorld) ctx.getBean("HelloWorld.class");
//根据类型来获取 bean 的实例: 要求在 IOC 容器中只有一个与之类型匹配的 bean, 若有多个则会抛出异常.
//一般情况下, 该方法可用, 因为一般情况下, 在一个 IOC 容器中一个类型对应的 bean 也只有一个.
// HelloWorld helloWorld1 = ctx.getBean(HelloWorld.class);
//3. 使用 bean
helloWorld.hello();
}
缺陷 : 若在xml中定义了多个Bean,那么会报错
<bean id="helloWorld1" class="atguigu.Spring.HelloWorld">
<property name="user" value="kaizuidebanli"/>
</bean>
<bean id="helloWorld2" class="atguigu.Spring.HelloWorld">
<property name="user" value="kaizuidebanli"/>
</bean>