spring in action 学习笔记五:@Autowired这个注解如何理解

  @Autowired这个注解的意思就是自动装配。他把一个bean对象自动装配到另一个对象中。下面的案例证明了spring的自动装配。

定义一个Sixi类。代码如下:

 1 package com.qls.autowired.soundsystem;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 5 /**
 6  * Created by ${秦林森} on 2017/6/8.
 7  */
 8 @Component
 9 public class Sixi {
10     private String name;
11 
12     public String getName() {
13         return name;
14     }
15 
16     public void setName(String name) {
17         this.name = name;
18     }
19 }

定义一个Ouyangfeng类,这个类中把Sixi类自动装配进来,代码如下:

package com.qls.autowired.soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by ${秦林森} on 2017/6/8.
 */
@Component
public class Ouyangfeng {
    /**
     * @Autowired这个注解是自动装配。
     * 何为装配?the act of creating associations between application component is commonly referred
     * to as wiring(装配)。
     * 建立各个组件之间的联系的行为称为装配。
     * 何为自动装配:spring框架帮你装配。
     */
    @Autowired
    private Sixi sixi;
    public void ouyangfeng(){
        System.out.println("欧阳凤是泗溪村的大学生村官");
    }
    public Sixi getSixi(){
        return sixi;
    }
}

定义一个配置类:代码如下:

 1 package com.qls.autowired.soundsystem;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Component;
 5 
 6 /**
 7  * Created by ${秦林森} on 2017/6/8.
 8  */
 9 @Component
10 public class Ouyangfeng {
11     /**
12      * @Autowired这个注解是自动装配。
13      * 何为装配?the act of creating associations between application component is commonly referred
14      * to as wiring(装配)。
15      * 建立各个组件之间的联系的行为称为装配。
16      * 何为自动装配:spring框架帮你装配。
17      */
18     @Autowired
19     private Sixi sixi;
20     public void ouyangfeng(){
21         System.out.println("欧阳凤是泗溪村的大学生村官");
22     }
23     public Sixi getSixi(){
24         return sixi;
25     }
26 }

定义一个测试类:代码如下:

package com.qls.autowired.soundsystem;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by ${秦林森} on 2017/6/8.
 */

public class AutoWiredTest {
    public static void main(String[] args) {
        /**
         * AnnotationConfigApplicationContext
         */
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoWiredConfig.class);
        Sixi sixi = ac.getBean(Sixi.class);
        Ouyangfeng ouyangfeng = ac.getBean(Ouyangfeng.class);
        /**
         * 从Ouyangfeng这个类得到的Sixi这个对象如果和从容器中得到的Sixi对象相等,
         * 则说明spring已经完成自动装配。
         */
        System.out.println(ouyangfeng.getSixi()==sixi);

    }
}/**output:ture
 */
 

从测试类的结果可以看出Sixi这个bean确实已经自动装配到Ouyangfengz这个类中了。

 

posted @ 2017-06-08 09:31  技术让世界更精彩  阅读(1002)  评论(0编辑  收藏  举报