这是一个不平凡的变化。一个@Configuration
类(或者更确切地说AnnotationConfigApplicationContext
)注册了一个CommonAnnotationBeanPostProcessor
,它负责调用一个bean的@PostConstruct
方法。改变这将意味着几乎改变了整个Spring IoC栈。
其实,你可以只声明CommonAnnotationBeanPostProcessor
一个bean名称org.springframework.context.annotation.internalCommonAnnotationProcessor
这将覆盖默认值。您可以将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方法永远不会被调用。
我不明白:你有一个'@ Bean' problematicService(),你在那里构造一个'ProblematicService',但是你说它是“由其他代码为我构建的”。你想说你可以从API访问'ProblematicService',并且你需要构建它,但是API带有@ PostConstruct注解,你不能改变它? –
是的,有问题的服务对我来说已经从我的控制之外的代码构建。 –
你们每个人都打算调用'@ PostConstruct'注释的方法吗?而“ProblematicService”声明为“final”? –