Spring的注解@AutoWired主要是对类的成员变量进行自动装配工作。
例如有两个实体Subs和SubsOper,SubsOper存放Subs的具体业务方法,将SubsOper作为Subs的成员变量存在。
SubsOper.java
public class SubsOper {
public SubsOper() {
System.out.println("this is the SubsOper constructor...");
}
public void changePsw() {
System.out.println(this.name+" begin to change password...");
}
}
Subs.java
public class Subs {
@Autowired
private SubsOper subsOper;
public void changePsw() {
subsOper.changePsw();
}
}
bean.xml 配置文件配置如下,注意context的部分,这个是必须的,否则@AutoWired不会生效。
<?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/>
<bean id="Subs" class="com.dicover.Subs"/>
<bean id="SubsOper" class="com.dicover.SubsOper"/>
</beans>
写一个测试类AutoWiredTest.java来看看执行的结果
public class AutoWiredTest {
/**
* Description: <br>
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Subs subs = context.getBean("Subs", Subs.class);
subs.changePsw();
}
}
执行结果:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
this is the SubsOper constructor...
begin to change password...
this is the SubsOper constructor打印出来表明subsOper对象自动初始化成功,否则如果没有用@AutoWired就会报空指针异常,begin to change password打印出来表明能够调用到SubsOper中的方法。
</pre><pre code_snippet_id="1581546" snippet_file_name="blog_20160218_8_4298723" name="code" class="plain">