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"/>
@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不为null。
答案 0 :(得分:0)
问题似乎是cdiExample,你的测试用例不是一个spring bean。您可以在@Before中手动实例化它。
而是试试这个:
function getSections(names, cb) {
var obj = {};
names.forEach(function (name) {
obj[name] = cb(x, y);
});
return obj;
}
// Used as
getSections(['tense', 'person', 'number', 'voice'], randomIntFromInterval);
这样cdiExample将从弹簧上下文中注入,弹簧上下文将由spring自动装配。