我正在使用带有 SpringBoot 的 Spring 4 和带有 Java 配置的 Spring-Web。
拥有我的@PostConstruct
Spring 在启动时执行的注解方法,需要将 CommonAnnotationBeanPostProcessor
注册到上下文中,否则 @PostConstruct
将被忽略。
在基于 XML 的 Spring 配置中,文档说要使用(在 beans 元素下)
<context:annotation-config/>
我还看到了一个基于单个 bean 完成注册的示例,如下所示:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
如果可能的话,我希望避免这种情况。我的项目不包含任何 XML 文件,并且在我的构建文件夹中没有为我生成任何文件。
目前,我的解决方案是用 @ComponentScan
注释我的类,我相信这会导致 Spring 检测并注册 @Component
s 和 @Bean
s。
不知何故,这会导致 CommonAnnotationBeanPostProcessor
被调用,虽然我不知道为什么,但它解决了我的问题!
(该类有一个 @Autowired
属性,在启动时为 null - 因此需要通过 @PostConstruct
进行初始化)
但是,我的问题是,使用 Java 配置实现此目的的正确方法是什么?谢谢!
最佳答案
您可以使用 InitializingBean作为替代解决方案。
只需扩展此接口(interface)并覆盖 afterPropertiesSet设置完 bean 的所有属性后调用的方法,就像 post 构造一样。
例如:
@Component
public class MyBean implements InitializingBean
{
@Override
public void afterPropertiesSet()
{
// do whatever you want to do here
}
}
关于spring - 通过 Java 配置通过 CommonAnnotationBeanPostProcessor 激活 @PostConstruct 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34154413/
相关文章:
java - 运行 find 会抛出一个 Detached 实体传递给持久异常
java - 单个 hibernate session 中的多个事务(使用 Spring)
Java - 避免创建空的子类和接口(interface)或生成 Java 源代码模板
java - 使用spring boot(安全)和keycloak启用角色身份验证?
spring - Spring JUnit 测试中的自动模拟实例化
java - Spring Boot + Spring Data Multi-Tenancy
spring - @PreAuthorize(permitAll) 仍然需要身份验证
java - Spring MVC 3.2 - 错误页面的内容协商?