Spring 是否可以使用特定的bean初始化来附加BeanPostProcessor

Spring 是否可以使用特定的bean初始化来附加BeanPostProcessor,spring,Spring,我想知道是否有可能定义一个只能对特定bean执行的BeanPostProcessor类 根据配置,我可以有如下所述的2个bean。这里,InitHelloWorld正在实现BeanPostProcessor初始化前的后处理和初始化后的后处理方法在此处被覆盖。所有初始化的bean都会调用这些方法。我希望仅为com.tutorialspoint.HelloWorld <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"

我想知道是否有可能定义一个只能对特定bean执行的
BeanPostProcessor

根据配置,我可以有如下所述的2个bean。这里,
InitHelloWorld
正在实现
BeanPostProcessor
<代码>初始化前的后处理和初始化后的后处理方法在此处被覆盖。所有初始化的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" />

在定义方法时尝试检查类本身,例如:

public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { 
    if (bean.getClass().equals(HelloWorld.class)) {
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { 
        ......
    }

考虑在这些类上使用一些
标记
注释:

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;
}
public Object postProcessBeforeInitialization(最终对象bean,最终字符串beanName)抛出BeansException{
Class targetClass=AopUtils.getTargetClass(bean);
if(AnnotationUtils.findAnnotation(beanClass,MyMarker.class)!=null){
....
返回豆;
}
返回豆;
}

一个简单的if语句检查后处理器初始化中的类实例,可以实现以下目的:

if (bean instanceof HelloWorld){...}

把它放在上下文中:

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof HelloWorld){
        System.out.println("This only prints for an instance of HelloWord");
    }

在一段时间内,会有很多这样的情况。所以我想避免使用这个。如果我从应用程序中删除任何bean,那么这样做也将是另一个问题,因为我需要一次又一次地重新访问此文件。因此,我建议您在属性文件中插入一个属性,并使用属性中定义的bean检查beanName。这是正确的方法。Spring对方面也使用相同的方法。
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof HelloWorld){
        System.out.println("This only prints for an instance of HelloWord");
    }