@Autowired注解【Spring入门】

前一篇文章写了在使用Spring框架过程中,通过在头标签中加入默认default-autowire来自动装配,但是该方法有一定局限性,就是需要被装配类中有setter方法,且setter方法有一定要求。

现在,使用@Autowired注解方法(byType),就可以省去setter方法,进行自动装配。

首先,要在spring配置文件中加入

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

或者使用包括上面标签的扫描标签:

<context:component-scan/>

这是Spring解析@Autowired要用到的bean。

代码示例:

package com.yykj;

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

public class CDPlayer {
    @Autowired
    private CD cd;

    public void play(){
        cd.Play();
    }
}


当然,@Autowired注解不仅可以在成员变量上使用,也可以在setter方法和构造器上进行自动注入。

代码如下:

package com.yykj;

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

public class CDPlayer {

    private CD cd;

    @Autowired
    public CDPlayer(CD cd){
        this.cd = cd;
    }
    
    @Autowired
    public void setCd(CD cd) {
        this.cd = cd;
    }

    public void play(){
        cd.Play();
    }
}


也可以使用@Autowired注解来给一个集合(如Map,List,Set)赋值注入所有相同类型的bean。下面给出代码:

package com.yykj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class BeanInvoker {

    @Autowired
    private List<BeanInterface> list;

    @Autowired
    private Map<String, BeanInterface> map;//Key是bean的name,默认为类名(首字母小写)

    @Autowired
    private Set<BeanInterface> set;

    public void travel(){
        for (BeanInterface b : list) {
            System.out.println(b.getClass().getName());
        }

        for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }

        for (BeanInterface b : set) {
            System.out.println(b.getClass().getName());
        }
    }
}
另外,在List集合中的元素组件bean开头加上@Order标签,可以使得List数组按照@Order内的值对元素组件bean进行排序。

原理:Spring容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,若发现某个bean类型与注解下的成员变量或setter方法,构造器等方法的参数相同时,则会自动注入。但是在自己写的实现BeanPostProcessor接口的类中不能使用@Autowired注解,因为这样会引起循环依赖。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值