大佬教程收集整理的这篇文章主要介绍了使用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中会产生预期的效果,但我需要在几个地方重复这段代码,所以我正在寻找更优雅的解决方案.
实际上,您可以使用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.
@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();
}
以上是大佬教程为你收集整理的使用Java Config时如何防止Spring生命周期方法?全部内容,希望文章能够帮你解决使用Java Config时如何防止Spring生命周期方法?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。