Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析
一.生命周期
-
@Bean自定义初始化和销毁方法
//====xml方式: init-method和destroy-method==== <bean id="person" class="com.hrh.bean.Person" scope="singleton" init-method="" destroy-method=""> <property name="name" value="张三"></property> <property name="age" value="20"></property> </bean> //====@Bean方式==== /** *单实例:只调用initMethod一次,容器关闭时会调用destroyMethod *多实例: 每次调用Bean都调用initMethod,容器关闭不会调用destroyMethod,需要手动调用 **/ @Bean(initMethod = "",destroyMethod = "") public Person person() { System.out.println("注入容器。。。。。"); return new Person("张三", 20); } //====实现接口方式==== /** * InitializingBean:定义初始化逻辑,实现afterPropertiesSet() * DisposableBean:定义销毁逻辑,实现destroy() */ @Component public class Person implements InitializingBean, DisposableBean { public Person(){ System.out.println("Person 。。。 constructor"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("Person 。。。afterPropertiesSet"); } @Override public void destroy() throws DestroyFailedException { System.out.println("Person 。。。destroy"); } } @Configurable @ComponentScan(value = "com.hrh") public class BeanConfig {} AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); context.close();
-
@PostConstruct和@PreDestroy
/** * JSR250: * @PostConstruct: 在bean创建完成并且属性赋值完成后,来执行初始化方法 * @PreDestroy :在容器销毁bean之前通知进行清理工作 */ @Component public class Color { public Color() { System.out.println("Color 。。。 constructor"); } @PostConstruct//对象创建并赋值之后调用 public void init() throws Exception { System.out.println("Color 。。。init"); } @PreDestroy//容器移除对象之前 public void destroy() { System.out.println("Color 。。。destroy"); } }
-
BeanPostProcessor:bean后置处理器,对bean初始化之前和之后的处理,上文的@PostConstruct和@PreDestroy就是使用了该类实现的
-
案例:
@Component public class MyBeanPostProcessor implements BeanPostProcessor { /** * * @param bean 容器创建的实例 * @param beanName 容器创建实例的名字 * @return 创建的实例或进行包装后的实例 * @throws BeansException */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization====>【"+bean+"】:"+beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization====>【"+bean+"】:"+beanName); return bean; } } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); }
-
BeanPostProcessor是Spring IOC容器给我们提供的一个扩展接口。
public interface BeanPostProcessor { //bean初始化方法调用前被调用 Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; //bean初始化方法调用后被调用 Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }
接口提供了两个方法,分别是初始化前和初始化后执行方法,具体这个初始化方法指的是什么方法,类似我们在定义bean时,定义了init-method所指定的方法<bean id = "xxx" class = "xxx" init-method = "init()">或@Bean(initMethod = "init()")
这两个方法分别在init方法前后执行,需要注意一点,我们定义一个类实现了BeanPostProcessor,默认是会对整个Spring容器中所有的bean进行处理。
既然是默认全部处理,那么我们怎么确认我们需要处理的某个具体的bean呢?
可以看到方法中有两个参数。类型分别为Object和String,第一个参数是每个bean的实例,第二个参数是每个bean的name或者id属性的值。所以我们可以第二个参数,来确认我们将要处理的具体的bean。
这个的处理是发生在Spring容器的实例化和依赖注入之后。
运行流程:
1)Spring IOC容器实例化Bean;
2)调用BeanPostProcessor的postProcessBeforeInitialization方法;
3)调用bean实例的初始化方法;
4)调用BeanPostProcessor的postProcessAfterInitialization方法;
BeanPostProcessor接口作用:
如果我们想在Spring容器中完成bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。我们需要定义一个或多个BeanPostProcessor接口实现类,然后注册到Spring IoC容器中。
Spring中Bean的实例化过程图示:
-
-
原理:从doCreateBean可以看到,在对bean进行属性赋值后,调用initializeBean初始化bean,在initializeBean中会在调用初始化方法前后会遍历所有的BeanPostProcessor实现的方法
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { .... refresh();//刷新容器 } public void refresh() throws BeansException, IllegalStateException { ... //初始化剩下所有的(非懒加载的)单实例对象 finishBeanFactoryInitialization(beanFactory); } protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { ... //初始化剩下所有的(非懒加载的)单实例对象 beanFactory.preInstantiateSingletons(); } public void preInstantiateSingletons() throws BeansException { ... getBean(beanName); ... } @Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { ... //getSingleton获取实例 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args);//创建实例 } ... } }); ... return (T) bean; } protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { ... Object beanInstance = doCreateBean(beanName, mbdToUse, args);//创建实例 ... return beanInstance; } protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { ... Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper);//对属性赋值 if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd);//初始化对象,相当后置处理器的调用 } } ... return exposedObject; } //从下面可以看到,在执行初始化方法之前,执行applyBeanPostProcessorsBeforeInitialization,执行完初始化方法之后,执行applyBeanPostProcessorsAfterInitialization protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { ... wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); ... invokeInitMethods(beanName, wrappedBean, mbd);//执行初始化方法 ... wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); return wrappedBean; } @Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; //遍历执行实现了BeanPostProcessor接口的类,比如MyBeanPostProcessor,然后执行实现类的重写方法 for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessBeforeInitialization(result, beanName); if (result == null) { return result; } } return result; }
-
-
-
InitDestroyAnnotationBeanPostProcessor:处理@PostConstruct和@PreDestroy
/** * 处理javax.annotation.PostConstruct注解 */ public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) { this.initAnnotationType = initAnnotationType; } /** * 处理javax.annotation.PreDestroy注解 */ public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) { this.destroyAnnotationType = destroyAnnotationType; } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //找到了使用@PostConstruct和@PreDestroy的类的生命周期注解 LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); try { //对每个注解上的方法进行反射执行 metadata.invokeInitMethods(bean, beanName); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Failed to invoke init method", ex); } return bean; } public void invokeInitMethods(Object target, String beanName) throws Throwable { Collection<LifecycleElement> checkedInitMethods = this.checkedInitMethods; Collection<LifecycleElement> initMethodsToIterate = (checkedInitMethods != null ? checkedInitMethods : this.initMethods); if (!initMethodsToIterate.isEmpty()) { for (LifecycleElement element : initMethodsToIterate) { if (logger.isTraceEnabled()) { logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod()); } //element包含注解和注解上的方法 element.invoke(target);//执行每个注解上的方法 } } }
-
二.属性赋值
-
@Value
public class Person { /** * @Value :基本数值,SpEL表达式 #{}, ${}获取配置文件的值 */ @Value("张三") private String name; @Value("#{20-1}") private Integer age; }
-
@PropertySource:读取外部配置文件中k/v的数据
public class Person{ /** * @Value :基本数值,SpEL表达式 #{}, ${}获取配置文件的值 */ @Value("张三") private String name; @Value("#{20-1}") private Integer age; @Value("${sex}") private String sex; } @PropertySource(value = "classpath:/global.properties") @Configurable public class BeanConfig {} global.properties sex=男
三.自动装配
-
@Autowired&@Qualifier&@Primary:Spring定义
@Service public class UserService { /** * @Autowired :自动注入 * 1)默认优先按照类型去容器中对应的组件:context.getBean(UserDao.class); * 2)如果有多少相同类型的组件,需要将属性的名称作为id去容器查找:(UserDao) context.getBean("userDao1") * 3)@Qualifier("userDao1"):指定需要装配的组件id,而不是使用默认属性;优先级比@Primary高 * 4)如果UserDao没有注入容器(@Repository和 @Bean):启用@Autowired会报空指针异常,需要required = false,表示从容器中找到就自动装配,找不到就设为null * 5)@Primary表示Spring自动装配时,默认使用首选的bean */ @Qualifier("userDao") @Autowired private UserDao userDao; public void printf() { System.out.println(userDao); } } @Repository public class UserDao { private String id ="1"; public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "UserDao{" + "id='" + id + '\'' + '}'; } } @Configurable @ComponentScan(value = "com.hrh") public class BeanConfig { @Primary @Bean("userDao1") public UserDao userDao() { UserDao userDao = new UserDao(); userDao.setId("2"); return userDao; } } AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class); UserService person = context.getBean(UserService.class); person.printf(); //UserDao userDao = context.getBean(UserDao.class); UserDao userDao =(UserDao) context.getBean("userDao1"); System.out.println(userDao);
-
@Resource&@Inject:Java规范
-
@Resource:只按照属性名称进行装配,可以使用@Resource(name = "")装配指定id;不支持@Primary的使用,即使用该注解是无效的;
-
@Inject:支持自动装配,和@Autowired功能一样,支持@Primary的使用;没有required = false属性;
-
-
Aware注入Spring底层组件&原理
-
自定义组件使用Spring容器底层的一些组件(ApplicationContext、BeanFactory...),实现xxxAware
public class Color implements ApplicationContextAware { private ApplicationContext applicationContext; //获取容器并赋值给当前类 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
-
xxxAware使用对应的xxxAwareProcessor进行处理:利用后置处理器在类初始化时注入组件
//bean:获得实现了ApplicationContextAware接口的类,即Color public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { //类型判断 if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware || bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){ return bean; } AccessControlContext acc = null; if (System.getSecurityManager() != null) { acc = this.applicationContext.getBeanFactory().getAccessControlContext(); } if (acc != null) { //权限检查 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareInterfaces(bean); return null; }, acc); } else { invokeAwareInterfaces(bean);//转换并注入组件 } return bean; } private void invokeAwareInterfaces(Object bean) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { //给当前类注入ApplicationContext ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } }
-
-
@Profile:指定组件在哪个环境的情况下才能被注册到容器中
- 加了环境标识的bean,只有在指定环境才能被注册到容器中,默认是default环境
- 写在配置类上,只有是指定环境整个配置类里面的所有配置才能生效
- 没有环境标识的bean在任何环境下都会被注册到容器中
@PropertySource("classpaht:/db.properties") @Configuration public class BeanProfileConfig { @Value("${db.user}") private String user; @Value("${db.driverClass}") private String driverClass; @Profile("test") @Bean public DataSource TestDateSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser(user); dataSource.setPassword(pwd); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); dataSource.setDriverClass(driverClass); return dataSource; } @Profile("dev") @Bean public DataSource DevDateSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser(user); dataSource.setPassword(pwd); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev"); dataSource.setDriverClass(driverClass); return dataSource; } @Profile("pro") @Bean public DataSource ProDateSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser(user); dataSource.setPassword(pwd); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/pro"); dataSource.setDriverClass(driverClass); return dataSource; } } /** * 1.使用命令行动态参数:在虚拟机参数位置加载 -Dspring.profiles.active=test * 2.代码方式:创建无参容器,设置激活环境 */ //创建容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); //设置需要激活的环境 context.getEnvironment().setActiveProfiles("test"); //注册主配置类 context.register(BeanProfileConfig.class); //启动刷新容器 context.refresh();
作者:huangrenhui
欢迎任何形式的转载,但请务必注明出处。
如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】。
如果,您希望更容易地发现我的新博客,不妨点击一下左下角的【关注我】。
如果,您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客,我是【码猿手】。
如果,您希望更容易地发现我的新博客,不妨点击一下左下角的【关注我】。
如果,您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客,我是【码猿手】。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。