zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    Checking Types Against the Real World in TypeScript
    nexus pip proxy config
    go.rice 强大灵活的golang 静态资源嵌入包
    几个golang 静态资源嵌入包
    rpm 子包创建学习
    Rpm Creating Subpackages
    ava 类似jest snapshot 功能试用
    ava js 测试框架基本试用
    The Architectural Principles Behind Vrbo’s GraphQL Implementation
    graphql-compose graphql schema 生成工具集
  • 原文地址:https://www.cnblogs.com/binger/p/2701099.html
Copyright © 2011-2022 走看看