在Spring框架中,@PostConstruct注解、init-method属性、以及afterPropertiesSet()方法通常用于初始化Bean的逻辑。它们都提供了在Bean创建和初始化完成后执行的方法,但执行顺序有所不同。 想要知道@PostConstruct、init-method、afterPropertiesSet()的执行顺序,只要搞明白它们各自在什么时候被谁调用就行了。 代码如下: 1 2 3...
<bean id="person" class="zd.dms.job.ebuy.Person" autowire="byType" destroy-method="destory" init-method="init" scope="prototype"></bean> 我们多次访问Action,所以Action会多次调用Person对象,发现会多次创建Person对象,也就是请求一次会创建一个对象,也就是多例: 至于到底是该使用单例还是多例,这就...
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE); if (!"".equals(initMethodName)) { bd.setInitMethodName(initMethodName); } } else { if (this.defaults.getInitMethod() != null) { bd.setInitMethodName(this.defaults.getInitMethod()); bd.setEnforceInitMethod(false); } } i...
initMethod和InitializingBean指定方法的执行顺序在普通属性装配之后,initMethod指定的方法又在InitializingBean指定的方法之后执行。 @PostConstruct、InitializingBean、initMethod执行顺序如下: Construction > 对象属性set() 方法-> @PostConstruct -> InitializingBean -> initMethod...
2. @Bean init-method标签 这个在比较古早的xml版本中已经实现,如<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>,而在Spring高版本中,可以使用注解的方式配置。 @Slf4jpublicclassInitMethodBean{@AutowiredprivateEnvironmentenv;publicvoidinit(){log.info("Invoke InitMethodBean#...
二、破解:使用Spring的init() 对于这种,需要在Spring初始化之后做一些事情的话,那么怎么破呢? 对于初始化数据常用的有3种实现方式: (1)使用JSR-250规范定义的@Postconstruct注解。 (2)使用Spring提供的@Bean init-method标签。 (3)实现InitializingBean接口,实现afterPropertiesset()方法。 对于这3种方式的使用,我们...
@PostConstruct、init-method、afterPropertiesSet() 执行顺序 想要知道 @PostConstruct、init-method、afterPropertiesSet() 的执行顺序,只要搞明白它们各自在什么时候被谁调用就行了。 程序版本:Spring Boot 2.3.5.RELEASE 准备好要验证的材料: publicclassFooimplementsInitializingBean{ ...
@Bean(initMethod="init")publicvoidinit3(){log.info("通过配置@bean的init-method属性,实现项目启动时加载缓存...");}} 测试结果展示: 由此可以看出: 优先级: 构造方法 >@PostContruct>afterPropertiesSet()>init-method
想到了什么?在也谈Spring容器的生命周期中,我们提到过BeanPostProcessor的postProcessBeforeInitialization是在Bean生命周期中afterPropertiesSet和init-method之前执被调用的。 再次观察CommonAnnotationBeanPostProcessor这个类,它继承自InitDestroyAnnotationBeanPostProcessor。InitDestroyAnnotationBeanPostProcessor顾名思义,就是在...
实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖 先调用afterPropertiesSet,再执行 init-method 方法,如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。@...