init-method属性是Spring Bean的一个属性,它允许我们指定一个初始化方法。这个方法会在Bean实例化并完成属性注入后自动执行。与@PostConstruct注解不同的是,init-method属性并不依赖于Spring容器,因此可以在没有Spring的环境中运行。 afterPropertiesSet是SpringFramework中的一个初始化方法,它属于 InitializingBean接口的一部分。
packagecom.nrsc.springstudy.c071_InitializingBean_initMethod_PostConstruct.config;importcom.nrsc.springstudy.c071_InitializingBean_initMethod_PostConstruct.beans.Cat;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration; @ConfigurationpublicclassC071Config { @...
spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖 先调用afterPrope...
bd.setEnforceInitMethod(false); } } if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) { String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE); if (!"".equals(destroyMethodName)) { bd.setDestroyMethodName(destroyMethodName); } } else { if (this.defaults.getDestroyMethod() != ...
@PostConstruct、init-method、afterPropertiesSet() 执行顺序 想要知道 @PostConstruct、init-method、afterPropertiesSet() 的执行顺序,只要搞明白它们各自在什么时候被谁调用就行了。 程序版本:Spring Boot 2.3.5.RELEASE 准备好要验证的材料: publicclassFooimplementsInitializingBean{ ...
1、Spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用。 2、实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率要高一点,但是init-method方式消除了对spring的依赖。
@Bean(initMethod="init")publicvoidinit3(){log.info("通过配置@bean的init-method属性,实现项目启动时加载缓存...");}} 测试结果展示: 由此可以看出: 优先级: 构造方法 >@PostContruct>afterPropertiesSet()>init-method
spring bean的初始化执行顺序:构造方法(依赖注入完成) --> @PostConstruct注解的方法 --> afterPropertiesSet方法 --> init-method指定的方法。具体可以参考例子afterPropertiesSet通过接口实现方式调用(效率上高一点),@PostConstruct和init-method都是通过反射机制调用...
2.1 初始化方法initMethod 这个以前是通过xml配置文件来定义的,现在可以直接定义在@Bean注解上,如下: @Bean(initMethod = "initMethod") public BeanLifeCheck beanLifeCheck() { return new BeanLifeCheck(); } 2.2 注解@PostConstruct 直接在方法上加注解即可: @PostConstruct public void postConstruct() { logge...
@PostConstruct、init-method、afterPropertiesSet() 执行顺序 想要知道 @PostConstruct、init-method、afterPropertiesSet() 的执行顺序,只要搞明白它们各自在什么时候被谁调用就行了。 程序版本:Spring Boot 2.3.5.RELEASE 准备好要验证的材料: public class Foo implements InitializingBean { ...