gpt4 book ai didi

java - 使用派生的 AbstractSingleBeanDefinitionParser 或其他方法在 BeanPostProcessor 中配置类

转载 作者:行者123 更新时间:2023-11-29 05:38:43 26 4
gpt4 key购买 nike

我有一个实现 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com