微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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方法.

原文地址:https://www.jb51.cc/spring/431513.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐