注解@AutoWired

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">

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值