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 { @...
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() != ...
spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖 先调用afterPrope...
@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
【Java面试题:@PostConstruct、init-method和afterPropertiesSet执行顺序?】的更多相关文章 浅谈Java语言中try{}catch{}和finally{}的执行顺序问题 浅谈Java语言中try{}catch{}和finally{}的执行顺序问题 2019-04-06 PM 13:41:46 1. 不管有没有出现异常,finally块中代码都会执行: 2. 当try和catch中有return时,...
2.1 初始化方法initMethod 这个以前是通过xml配置文件来定义的,现在可以直接定义在@Bean注解上,如下: @Bean(initMethod = "initMethod") public BeanLifeCheck beanLifeCheck() { return new BeanLifeCheck(); } 2.2 注解@PostConstruct 直接在方法上加注解即可: ...
2.1 初始化方法initMethod 这个以前是通过xml配置文件来定义的,现在可以直接定义在@Bean注解上,如下: @Bean(initMethod = "initMethod") public BeanLifeCheck beanLifeCheck() { return new BeanLifeCheck(); } 2.2 注解@PostConstruct 直接在方法上加注解即可: @PostConstruct public void postConstruct() { logge...