0
public interface Animal {
    public String getName();
    public int getAge();
}

@Component
public class Dog implements Animal{

    @Override public String getName() {
        return "Puppy";
    }

    @Override public int getAge() {
        return 10;
    }
}

@Component("cdiExample")
public class CDIExample {
    @Autowired
    private Dog dog;

    public void display() {
        try {
            System.out.println("com.example.Animal ---> " + dog.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:beans.xml");
            Animal animal=context.getBean("dog", Animal.class);
            System.out.println(animal.getName());
        }
    }

应用程序上下文

 <context:annotation-config/>
 <context:component-scan base-package="com.example"/>

Junit 测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {

    //@Autowired
    private CDIExample cdiExample;

    @Before
    public void before() throws Exception {
        cdiExample = new CDIExample();
    }

    @Test
    public void testDisplay() throws Exception {
        cdiExample.display();

    }

} 

测试上下文

<import resource="classpath*:/beans.xml" />

如果我运行上面的 Junittestcase,autowire 为空。

如果我执行 main 方法并使用 ClassPathXmlApplicationContext,bean 正在加载并且 autowire 不为空。

4

1 回答 1

0

问题似乎是您的测试用例中的 cdiExample 不是 spring bean。您在@Before 中手动实例化它。

而是试试这个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {

    @Autowired
    private CDIExample cdiExample;

    @Test
    public void testDisplay() throws Exception {
        cdiExample.display();

    }

} 

这样,cdiExample 将从 spring 上下文中注入,该上下文将通过 spring 自动装配 dog。

于 2015-05-28T22:01:50.070 回答