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

时间:2014-02-05 22:40:23

标签: java spring

我试图通过使用AutowireCapableBeanFactory.autowireBeanProperties()手动注入bean自动连接的依赖项。但是,如果应该注入的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();
  }
}

测试一些服务-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>

1 个答案:

答案 0 :(得分:1)

第二个测试用例失败,因为TestBean没有someService属性的setter,而context没有注册AutowiredAnnotationBeanPostProcessor

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