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 不为空。