作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个实现 springs BeanPostProcessor 的类 A
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 中。我如何使用 spring 配置(依赖注入(inject))这个类,这可能是因为它在 BeanPostProcessor 中......?
最佳答案
使用@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 can autodetect BeanPostProcessor beans in their bean definitions and apply them to any beans subsequently created.
大胆的我。
使用 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);
关于java - 使用派生的 AbstractSingleBeanDefinitionParser 或其他方法在 BeanPostProcessor 中配置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512446/
我有一个实现 springs BeanPostProcessor 的类 A public class A implements BeanPostProcessor { private B b;
我是一名优秀的程序员,十分优秀!