bean的作用域有两种,一种是单例模式,一种是多例模式。利用scope属性来设置。
<bean id="user" class="com.lu.Spring.pojo.User" scope="singleton">bean>
<bean id="user" class="com.lu.Spring.pojo.User" scope="prototype">bean>
| 属性值 | 含义 | 创建对象时机 |
|---|---|---|
| singleton | 单例模式,只创建唯一一个对象 | IOC容器初始化时 |
| prototype | 多例模式,可以创建多个对象。 | 获取bean时 |
bean的具体生命周期:
可以看到一个bean对象初始化到销毁要经过8个步骤,注意当IOC容器关闭时触发对象将其销毁。
当bean的作用域为prototype时,IOC容器关闭时对象也不会销毁。
FactoryBean是一个接口,包含三个方法,其他类实现该方法后可以直接配置bean当作工厂类使用。
public class UserFactory implements FactoryBean<User> {
public User getObject() throws Exception {
return new User();
}
public Class<?> getObjectType() {
return User.class;
}
// public boolean isSingleton() {
// return true;
// }
}
| 方法 | 作用 |
|---|---|
| getObject() | 返回工厂对应的类实例 |
| getObjectType() | 返回工厂对应的类类型 |
| isSingleton() | 返回的bean是否为单例模式,默认为true |
在Spring配置文件中配置UserFactory则会将User类交给IOC容器
<bean id="UserFactory" class="com.lu.Spring.factory.UserFactory">bean>
@Test
public void test() throws SQLException {
//1.获取ApplicationContext
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.获取指定类对象
User user = applicationContext.getBean(User.class);
System.out.println(user);
}
1、什么是自动装配
根据制定策略,在IOC匹配某一个bean自动为其类类型或者接口类型的属性赋值。
先来看看之前我们是怎么为其类类型或者接口类型的属性赋值的:

<bean id="userController" class="com.lu.Spring.controller.UserController" >
<property name="userService" ref="userServiceImpl">property>
bean>
<bean id="userServiceImpl" class="com.lu.Spring.service.Impl.UserServiceImpl" >bean>
可以看到我们通过ref属性手动为其装配。
我么接下来对xml文件中提供的两种常用的自动装配进行说明:autowire="byType"和autowire="byName"
2、自动装配–autowire=“byType”
<bean id="userController" class="com.lu.Spring.controller.UserController" autowire="byType">bean>
<bean id="userServiceImpl" class="com.lu.Spring.service.Impl.UserServiceImpl" >bean>
为UserController类对应的bean配置autowire="byType"属性,则会自动在IOC容器中查找对应的bean为其类类型或者接口类型的属性赋值。
3、自动装配–autowire=“byName”
<bean id="userController" class="com.lu.Spring.controller.UserController" autowire="byName">bean>
<bean id="userService" class="com.lu.Spring.service.Impl.UserServiceImpl" autowire="byName">bean>
通过autowire="byName"自动装配有一个注意点,自动装配时将会通过属性名作为id在IOC容器中自动装配对应的bean。所以要注意IOC容器中对应bean的id要和属性名一致。