2013-08-29 37 views
1

我有一個實現彈簧的BeanPostProcessor A類配置類中的BeanPostProcessor與衍生AbstractSingleBeanDefinitionParser或其他方法

public class A implements BeanPostProcessor { 


    private B b; 

    public A() { 
     b = new B(); 
     b.set(...);   
    } 


    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 
    return bean; 
    } 

    // Intercept all bean initialisations and return a proxy'd bean equipped with code 
    // measurement capabilities 
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 
    return b.enhance(bean); 
    } 


} 

我想配置我的B級其位於我的派生類的BeanPostProcessor A內部如何我可以配置(依賴注入)這個類與春天,這是可能的,因爲它內部的BeanPostProcessor ...?

+0

另請參閱http://stackoverflow.com/questions/1201726/tracking-down-cause-of-springs-not-eligible-for-auto-proxying/19688634#19688634如果您得到「Bean不符合條件由所有BeanPostProcessors處理「 –

回答

2

隨着@Configuration

public static class Child {} 

public static class Processor implements BeanPostProcessor {   
    @Autowired 
    public Child child;    
    @Override 
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 
     return null; // Spring would complain if this was executed 
    } 
    @Override 
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 
     return null; // Spring would complain if this was executed 
    }  
} 

@Configuration 
public static class Config { 
    @Bean 
    public static Processor processor() { 
     return new Processor(); 
    } 
    @Bean 
    public Child child() { 
     return new Child(); 
    } 
} 

public static void main(String[] args) throws IOException, ParseException, JAXBException, URISyntaxException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {  
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); 
    Processor processor = context.getBean(Processor.class); 
    System.out.println(processor.child); 
} 

BeanPostProcessor不「存在」,但這樣無法處理所創建的其他的bean(這是需要由@Autowired來完成這個bean)。該javadoc狀態

的ApplicationContexts可以在自己的 bean定義自動檢測BeanPostProcessor的豆子,並將其應用到隨後創建的任何豆

粗礦。

隨着XML

<context:component-scan base-package="test"></context:component-scan> 
<bean id="processor" class="test.Main.Processor"></bean> 
<bean id="child" class="test.Main.Child"></bean> 

ClassPathXmlApplicationContext xmlContext = new ClassPathXmlApplicationContext("context.xml"); 
processor = xmlContext.getBean(Processor.class); 
System.out.println(processor.child); 
1

你可以在你的BeanPostProcessor類的課程申請依賴注入。

下面是Spring Documentation

類實現了BeanPostProcessor接口比較特殊,所以他們被容器特別對待的摘錄。所有BeanPostProcessors及其直接引用的bean將在啓動時實例化,作爲ApplicationContext的特殊啓動階段的一部分,然後所有BeanPostProcessors將以已排序的方式註冊 - 並應用於所有其他bean。