gpt4 book ai didi

java - AutowireCapableBeanFactory.autowireBeanProperties() 似乎不适用于 xml 配置的上下文

转载 作者:行者123 更新时间:2023-11-30 11:22:40 25 4
gpt4 key购买 nike

我正在尝试使用 AutowireCapableBeanFactory.autowireBeanProperties() 手动注入(inject) bean Autowiring 依赖项。但它似乎只有在应该注入(inject)的 bean 是在 Java 类中配置的情况下才有效。如果它是在 XML 上下文文件中配置的,则它不起作用。

测试用例:

public class InjectorTest {

@Test
public void testAnnotationInjector() {
AnnotationConfigApplicationContext context = null;
try {
TestBean testBean = new TestBean();
context = new AnnotationConfigApplicationContext(SomeServiceConfig.class);;
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
beanFactory.autowireBeanProperties(testBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

assertTrue(testBean.getSomeService() != null);
} finally {
if (context != null) {
context.close();
}
}
}

@Test
public void testXmlInjector() {
ClassPathXmlApplicationContext context = null;
try {
TestBean testBean = new TestBean();
context = new ClassPathXmlApplicationContext("test-some-service-context.xml");
AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
beanFactory.autowireBeanProperties(testBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

assertTrue(testBean.getSomeService() != null);
} finally {
if (context != null) {
context.close();
}
}
}

private class TestBean {

@Autowired
private SomeService someService;

public SomeService getSomeService() {
return someService;
}
}

第一个测试用例运行成功。然而,第二个失败了。谁能解释这种行为?

下面是剩余的代码:

SomeService.java

public class SomeService {

public void doSomething() {
System.out.println("Did something");
}
}

JAVA上下文配置

@Configuration
public class SomeServiceConfig {

@Bean
public SomeService someService() {
return new SomeService();
}
}

test-some-service-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean class="webapplication.injector.SomeService"></bean>

</beans>

最佳答案

第二个测试用例失败,因为TestBean没有 someService 属性和上下文的 setter 没有注册 AutowiredAnnotationBeanPostProcessor

因此,要修复它,您可以为 someService 添加一个 setter 或添加一个 <context:annotation-config/>到 bean 定义文件。

关于java - AutowireCapableBeanFactory.autowireBeanProperties() 似乎不适用于 xml 配置的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590147/

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