我想知道是否可以定义一个只能针对特定bean执行的BeanPostProcessor
类。
根据配置,我可以有2个bean,如下所述。这里InitHelloWorld
正在实施BeanPostProcessor
。此处会覆盖postProcessBeforeInitialization
和postProcessAfterInitialization
方法。为所有初始化的bean调用这些方法。我希望只为com.tutorialspoint.HelloWorld
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
<bean id="helloWorld1" class="com.tutorialspoint.HelloWorld1"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
<bean class="com.tutorialspoint.InitHelloWorld" />
答案 0 :(得分:1)
考虑在这些类上使用一些marker
注释:
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
Class<?> targetClass = AopUtils.getTargetClass(bean);
if (AnnotationUtils.findAnnotation(beanClass, MyMarker.class) != null) {
....
return bean;
}
return bean;
}
答案 1 :(得分:0)
在定义类似的方法时尝试检查类本身:
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
if (bean.getClass().equals(HelloWorld.class)) {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
......
}
答案 2 :(得分:0)
在postProcessor初始化中检查类实例的简单if语句将起到作用,即:
if (bean instanceof HelloWorld){...}
或
if (bean.getClass().equals(HelloWorld.class)){...}
将其置于上下文中:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof HelloWorld){
System.out.println("This only prints for an instance of HelloWord");
}