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..."); } }
public class Subs { @Autowired private SubsOper subsOper; public void changePsw() { subsOper.changePsw(); } }
<?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"> <span style="color:#ff0000;"><context:annotation-config/></span> <bean id="Subs" class="com.dicover.Subs"/> <bean id="SubsOper" class="com.dicover.SubsOper"/> </beans>
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中的方法。