基于上一篇博客,又扩展出自动注入的代码部分。
扩展出自动注入的测试类如下:
public class AutowiredTest {
@Autowired
private man manTest;
@Autowired
private woman womanTest;
public void Run()
{
manTest.say("自动注入的男人");
womanTest.say("自动注入的女人");
}
}
主函数如下:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AutowiredTest autowiredTest = (AutowiredTest) context.getBean("autowiredTest");
autowiredTest.Run();
}
要用spring,要有配置文件,配置文件的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>
<context:annotation-config />
<context:component-scan base-package="com.spring.test"/>
<bean id="autowiredTest" class="com.spring.test.AutowiredTest"/>
</beans>
运行结果
男人类自动注入的男人
女人类自动注入的女人