使用Java Config时如何防止Spring生命周期方法?

在返回对象后,如何防止问题服务器上的@postconstruct方法Spring调用

@Configuration
class MyConfig {
    @Bean
    public ProblematicService problematicService() {
        ProblematicService service = someMethodoutsideMyControl();
        // ProblematicService is constructed for me by other code (outside of Spring)
        // and it happens to have a @postconstruct method. The @postconstruct method
        // cannot be invoked here or by Spring once this method returns.
        return service;
    }
}

我相信将结果包装在factorybean中会产生预期的效果,但我需要在几个地方重复这段代码,所以我正在寻找更优雅的解决方案.

最佳答案
这是一个非平凡的变化. @Configuration类(或者更确切地说是AnnotationConfigApplicationContext)注册一个CommonAnnotationBeanPostProcessor,它负责调用bean的@postconstruct方法.改变这意味着几乎改变整个Spring IoC堆栈.

实际上,您可以使用bean名称org.springframework.context.annotation.internalCommonAnnotationProcessor声明CommonAnnotationBeanPostProcessor,它将覆盖名称.您可以将init注释类型设置为null,以便它忽略@postconstruct.

@Bean(name = "org.springframework.context.annotation.internalCommonAnnotationProcessor")
public CommonAnnotationBeanPostProcessor commonAnnotationBeanPostProcessor() {
    CommonAnnotationBeanPostProcessor bean = new CommonAnnotationBeanPostProcessor();
    bean.setinitAnnotationType(null);;
    return bean;
}

使用它时要小心,否则可能会破坏其他东西.

我将首先建议尝试找到解决方法.例如,返回一个包装器对象,它可以让您访问ProblematicService.

@Bean
public ServiceProvider provider() {
    ProblematicService service = ...;
    ServiceProvider provider = new ServiceProvider(service);
    return provider;
}

或者类似你建议的factorybean.

一个更酷但更丑陋的方法是将对象包装在cglib代理中.

@Bean
public ProblematicService service() {
    ProblematicService service = ...;
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(service.getClass());
    enhancer.setCallback(new MethodInterceptor() {
        ProblematicService inner = service;
        @Override
        public Object intercept(Object obj,Method method,Object[] args,MethodProxy proxy) throws Throwable {
            if (!method.getName().equals("initMethodName"))
                return method.invoke(inner,args);
            return null;
        }
    });
    return (ProblematicService) enhancer.create();
}

基本上,永远不能调用init方法.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...