• spring的自动装配和精确装配


    spring提供了@Autowired Annotation来指定自动装配,使用@Autowired可以标注setter方法、普通方法、Field、函数形参和构造器等。

    例如下代码:

     1 package cn.zj.qiao.spring.beans;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.stereotype.Component;
     5 
     6 import cn.zj.qiao.spring.interfaces.Axe;
     7 import cn.zj.qiao.spring.interfaces.Person;
     8 
     9 @Component
    10 public class Chinese implements Person {
    11     
    12     private Axe axe;
    13     
    14     @Autowired
    15     public void setAxe(Axe axe){
    16         this.axe = axe;
    17     }
    18     public Axe getAxe(){
    19         return axe;
    20     }
    21 
    22     @Override
    23     public void useAxe() {
    24         System.out.println(axe.chop());
    25     }
    26 
    27 }

    上面的代码使用@Autowired 指定setAxe()方法进行自动装配,spring将会自动搜索容器中类型为Axe的Bean实例,并将该Bean实例作为setAxe()方法的参数传入,此时spring默认的装配策略为byType。同样的@Autowired可以修饰普通的方法,Field和构造器等,且其默认的装配策略均为byType类型的装配。

    为了实现精确的自动装配,spring提供了@Qualifier Annotation,通过使用@Qualifier,允许根据Bean的标识来指定自动装配,如下代码所示:

     1 package cn.zj.qiao.spring.beans;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.beans.factory.annotation.Qualifier;
     5 import org.springframework.stereotype.Component;
     6 
     7 import cn.zj.qiao.spring.interfaces.Axe;
     8 import cn.zj.qiao.spring.interfaces.Person;
     9 
    10 @Component
    11 public class Chinese implements Person {
    12     
    13     @Autowired
    14     @Qualifier("steelAxe")
    15     private Axe axe;
    16     
    17     public void setAxe(Axe axe){
    18         this.axe = axe;
    19     }
    20     public Axe getAxe(){
    21         return axe;
    22     }
    23 
    24     @Override
    25     public void useAxe() {
    26         System.out.println(axe.chop());
    27     }
    28 
    29 }

    如上代码所示,Axe axe Field将使用自动装配,且精确的指定了被装配Bean的实例的名称是steelAxe。

  • 相关阅读:
    LeetCode 88. Merge Sorted Array
    LeetCode 75. Sort Colors
    LeetCode 581. Shortest Unsorted Continuous Subarray
    LeetCode 20. Valid Parentheses
    LeetCode 53. Maximum Subarray
    LeetCode 461. Hamming Distance
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 976. Largest Perimeter Triangle
    LeetCode 1295. Find Numbers with Even Number of Digits
    如何自学并且系统学习计算机网络?(知乎问答)
  • 原文地址:https://www.cnblogs.com/binger/p/2701099.html
Copyright © 2020-2023  润新知