1. 程式人生 > >Spring 基於註解的配置(二)(@Required,@Autowired, @Qualifier)

Spring 基於註解的配置(二)(@Required,@Autowired, @Qualifier)

@Required

應用範圍:bean屬性的setter方法

作用:檢查註解的Bean屬性是否在XML中進行配置,若未進行配置則容器會丟擲一個BeanInitializationException異常

使用方法:

方法一:

包函 <context:annotation-config />

<context:annotation-config /><bean id="Hello" class="com.spring.demo.Hello"><!-- <property name="name" value="ruanjianlin"/> -->

<property name="id" value="12" /></bean>

Hello.java

package com.spring.demo;import org.springframework.beans.factory.annotation.Required;/** * Created by ruanjianlin on 2017/9/27. */public class Hello {private String name;    private int id;    public Hello() {    }public Hello(String name, int

id) {this.name = name;        this.id = id;}public String getName() {return name;}@Requiredpublic void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public void say(){        System.out.println("hello");}@Overridepublic String toString
() {return "Hello{" +"name='" + name + '\'' +", id=" + id +'}';}}

執行的結果:

Property 'name' is required for bean 'Hello'

方法二:

 bean 配置檔案包函“RequiredAnnotationBeanPostProcessor

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/><bean id="Hello" class="com.spring.demo.Hello"><!-- <property name="name" value="ruanjianlin"/> --><property name="id" value="12" /></bean>

@Autowired的聯絡:

[email protected] 的必要屬性,建議使用@Required註解

2.每個類只能有一個構造器被標記為required=true(每個類有很多的構造器,預設的required=false)

3.如果因為找不到合適的bean或者含有多個Bean將會導致autowiring失敗丟擲異常,使用@Autowired(required=false)解決(主要用於構造方法和Bean setter方法上,也可以用於屬性上)

Autowired是一種函式,可以對成員變數方法建構函式進行標註,來完成自動裝配的工作,@Autowired標註可以放在成員變數上,也可以放在成員變數的set方法上。

這裡必須明確:@Autowired根據型別進行自動裝配的,如果需要按名稱進行裝配,則需要配合@Qualifier使用

Spring 2.5 引入了 @Autowired註釋,它可以對類成員變數、方法及建構函式進行標註,完成自動裝配的工作。 通過 @Autowired的使用來消除set get方法。

 Spring遇到一個在 setter方法中使用的 @Autowired註釋,setter方法會在方法中檢視執行 byType 自動連線

Setter方法中的@Autowired

Computer.java

package com.spring.Autowire;/** * Created by ruanjianlin on 2017/10/6. */public class Computer {publicComputer() {        System.out.println("You get a new computer");}public voidplay(){        System.out.println("The computer is working! ");}}

Human.java

package com.spring.Autowire;import org.springframework.beans.factory.annotation.Autowired;/** * Created by ruanjianlin on 2017/10/6. */public class Human {privateComputer computer;    public Human() {        System.out.println("The function of  Human constructor is working!");}publicHuman(Computer computer) {this.computer= computer;System.out.println("The function of  Human which has a parameter is working!");}publicComputer getComputer() {returncomputer;}@Autowiredpublic voidsetComputer(Computer computer) {this.computer= computer;System.out.println("The function of setComputer is working!");}public voidplay(){computer.play();}}

Autowired_Demo.xml配置:

<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>    <bean id="human"class="com.spring.Autowire.Human">    </bean>    <bean id="computer"class="com.spring.Autowire.Computer">    </bean></beans>

輸出結果:

The function of  Human constructor is working!

You get a new computer

The function of setComputer is working!

The computer is working!

呼叫的方法:

Human()

Computer()

setComputer(Computer computer)

play()

建構函式中的@Autowired

package com.spring.Autowire;import org.springframework.beans.factory.annotation.Autowired;/** * Created by ruanjianlin on 2017/10/6. */public class Human {privateComputer computer;    public Human() {        System.out.println("The function of  Human constructor is working!");}@AutowiredpublicHuman(Computer computer) {this.computer= computer;System.out.println("The function of  Human which has a parameter is working!");}publicComputer getComputer() {returncomputer;}public voidsetComputer(Computer computer) {this.computer= computer;System.out.println("The function of setComputer is working!");}public voidplay(){computer.play();}}

輸出結果:

You get a new computer

The function of  Human which has a parameter is working!

The computer is working!

執行的方法:

Human(Computer computer)

Computer()

play()

屬性中的@Autowired

Human.java

package com.spring.Autowire;import org.springframework.beans.factory.annotation.Autowired;/** * Created by ruanjianlin on 2017/10/6. */public class Human {@AutowiredprivateComputer computer;    public Human() {        System.out.println("The function of  Human constructor is working!");}publicHuman(Computer computer) {this.computer= computer;System.out.println("The function of  Human which has a parameter is working!");}publicComputer getComputer() {returncomputer;}public voidsetComputer(Computer computer) {this.computer= computer;System.out.println("The function of setComputer is working!");}public voidplay(){computer.play();}}

輸出結果:

The function of  Human constructor is working!

You get a new computer

The computer is working!

Disconnected from the target VM, address: '127.0.0.1:54693', transport: 'socket'

執行的方法:

Human()

Computer()

play()

屬性上的新增@AutowiredgetBean時並沒有呼叫setComputer(Computer computer)

原理解釋:

(1)Spring 通過一個 BeanPostProcessor  @Autowired進行解析,所以要讓 @Autowired起作用必須事先在 Spring容器中宣告 AutowiredAnnotationBeanPostProcessor Bean

@Autowired在成員上配置Spring將直接採用 Java反射機制Human中的computer 這個私有成員變數進行自動注入。所以對成員變數使用 @Autowired後,可將它的 setter方法(setComputer(Computer computer)

)從 Human中刪除。

(2) @Autowired對方法或建構函式進行標註:(按照本示例作解析)如果建構函式有一個形參,是computer@Autowired尋找和它型別匹配的 Bean(byType),將它作為Human (Computer computer)引數來建立 Human Bean 此時不再呼叫setter方法,而@Autowiredsetter上時會通過上述方式進行Bean的註冊,而不會呼叫帶引數的建構函式

(3)在使用Spring框架中@Autowired標籤時預設情況下使用@Autowired 註釋進行自動注入時,Spring容器中匹配的候選 Bean數目必須有且僅有一個。當找不到一個匹配的 Bean時,Spring 容器將拋BeanCreationException異常,並指出必須至少擁有一個匹配的 Bean因此可以使用 @Qualifier解除歧義

@Qualifier的使用

@Autowired 可以對成員變數、方法以及建構函式進行註釋,而 @Qualifier 的標註物件是成員變數方法入參建構函式入參

程式碼示例:

Sing介面類:

package com.spring.Autowire;import org.springframework.stereotype.Component;/** * Created by ruanjianlin on 2017/10/7. */@Component("sing")public interface Sing {public voidsing();}

ManSing.java

package com.spring.Autowire;import org.springframework.stereotype.Component;/** * Created by ruanjianlin on 2017/10/7. */@Component("manSing")public class ManSingimplements Sing {public voidsing() {        System.out.println("This is a man!");}}

WomanSing.java

package com.spring.Autowire;import org.springframework.stereotype.Component;/** * Created by ruanjianlin on 2017/10/7. */@Component("womanSing")public class WomanSingimplements Sing {public voidsing() {        System.out.println("This is a woman!");}}

Human.java

package com.spring.Autowire;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;/** * Created by ruanjianlin on 2017/10/6. */public class Human {privateComputer computer;@Autowired    @Qualifier("manSing")privateSing sing;    public Human() {        System.out.println("The function of  Human constructor is working!");}@AutowiredpublicHuman(Computer computer) {this.computer= computer;System.out.println("The function of  Human which has a parameter is working!");}publicComputer getComputer() {returncomputer;}public voidsetComputer(Computer computer) {this.computer= computer;System.out.println("The function of setComputer is working!");}public voidsetSing(Sing sing) {this.sing= sing;}public voidplay(){computer.play();sing.sing();}}

Autowired_Demo.xml配置:

<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <context:annotation-config/>    <bean id="human"class="com.spring.Autowire.Human">    </bean>    <bean id="computer"class="com.spring.Autowire.Computer">    </bean>    <context:component-scanbase-package="com.spring"use-default-filters="false">        <context:include-filtertype="regex"expression="com.spring.Autowire.*"/>    </context:component-scan></beans>

上述為正確程式碼執行結果如下:

You get a new computer

The function of  Human which has a parameter is working!

The computer is working!

This is a man !

當我們不使用@Qualifier時報錯情況主要如下所示:

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.Autowire.Sing com.spring.Autowire.Human.sing; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.spring.Autowire.Sing] is defined: expected single matching bean but found 2: manSing,womanSing

錯誤解析:由報錯資訊可知產生了歧義,系統無法決定 manSing,womanSing

關於BeanPostProcessor介面相關的內容以及該介面的原理及工作機制,本人目前處於初級階段,尚無法解析,在後期進行原始碼學習時將會重點探索,望感興趣的猿們可以自行探索。

相關推薦

Spring 基於註解配置()(@Required,@Autowired, @Qualifier)

@Required 應用範圍:bean屬性的setter方法 作用:檢查註解的Bean屬性是否在XML中進行配置,若未進行配置則容器會丟擲一個BeanInitializationException異常 使用方法: 方法一: 包函 <context:annotatio

spring ioc---基於註解配置(beans包@Autowired,@Qualifier,@Required,@Value)

org.springframework.beans.factory.annotation包中的註解 註解 釋義 說明 原始碼註解說明(包含部分) @Autowired 自動裝配

Spring基於註解@Required配置

基於註解的配置 從 Spring 2.5 開始就可以使用註解來配置依賴注入。而不是採用 XML 來描述一個 bean 連線,你可以使用相關類,方法或欄位宣告的註解,將 bean 配置移動到元件類本身。 在 XML 注入之前進行註解注入,因此後者的配置將通過兩種方式的屬性連線被前者重寫。 註解連線在預設情況下在

Spring(七)之基於註解配置

關於 int ESS schema 控制 div except strong ont 基於註解的配置 從 Spring 2.5 開始就可以使用註解來配置依賴註入。而不是采用 XML 來描述一個 bean 連線,你可以使用相關類,方法或字段聲明的註解,將 bean 配置移動到

9.Spring——基於註解配置

元素 5.1 註解註入 視圖 col result ins ini llc 1.簡介 2.@Required 註釋 3.@Autowired 註釋 4.@Qualifier 註釋 5.JSR-250 註釋   5.1@PostConstruct 和 @PreDes

Java框架-Spring基於註解的IOC配置及純註解

註解配置與xml配置都實現了減低程式間耦合的功能。 不同公司由不同習慣,有可能是純xml、純註解(很少)或者xml與註解混合使用(基於註解的IOC配置)。 1. 基於註解的IOC配置 1.1 建立一個簡單案例 1.1.1 建立專案,新增依賴(pom.xml)

Spring基於註解的IoC配置

基於註解的IoC配置,與在xml中配置目的是一樣的,都是降低程式碼之間的耦合度的,只是配置的形式不一樣。 使用註解的步驟:     1、新增context的名稱控制元件和約束     2、開啟註解掃描:由spring掃描指定的包及其

Spring註解標籤詳解@Autowired @Qualifier

@Autowired spring2.1中允許使用者通過@Autowired註解對Bean的屬性變數.屬性Setter方法以及建構函式進行標註,配合AutowiredAnnotationBeanProcessor完成Bean的自動配置。使用@Autowired註釋進行byType注入。 在a

Spring(基於註解的IOC配置)

一、利用 spring的 IoC(xml配置)來實現賬戶的 CRUD[掌握] 步驟一:建立工程並匯入依賴(pom.xml:) <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/

Spring基於註解的AOP配置

Joinpoint(連線點): 所謂連線點是指那些被攔截到的點。在spring中,這些點指的是方法,因為spring只支援方法型別的連線點。指的是所有可以被增強的方法。 Pointcut(切入點): 所謂切入點是指我們要對哪些Joinpoint進行攔截的定義。指的是已經

Spring學習(穀粒學院spring4課程)第四節 基於註解配置bean

元件掃描(component scanning):  Spring 能夠從 classpath 下自動掃描, 偵測和例項化具有特定註解的元件. 特定元件包括: @Component: 基本註解, 標識了一個受 Spring 管理的元件 @Respository: 標識

Spring註解標籤詳解@Autowired @Qualifier等 @Slf4j

 @Slf4j @Slf4j註解實現日誌輸出       自己寫日誌的時候,肯定需要: private final Logger logger = LoggerFactory.getLogger(LoggerTest.class);1每次寫新的類

Spring基於註解的容器配置

首先用spring框架開發的程式設計師會有兩種用spring開發的風格 第一種就是我們spring配置的ApplicationContext.xml配置檔案 另一種就是我們spring的註解 這時候疑問來了,註解是否比配置Spring的XML更好? 答案當然不是絕對的! 基於註解的配置的

Spring註解標籤詳解@Autowired @Qualifier

@Autowired spring2.1中允許使用者通過@Autowired註解對Bean的屬性變數.屬性Setter方法以及建構函式進行標註,配合AutowiredAnnotationBeanProcessor完成Bean的自動配置。使用@Autowired註釋進行b

基於註解配置spring mvc 4 + spring security 4例項與解析

關於spring security 4(以下簡稱SS) ,我們不能不否認,學習的成本是挺高的。如果光光是複製配置程式碼而不去理解SS的各個元件的實現原理和功能,那當然還是相當簡單的一回事,因為配置的程式碼就那麼幾行 PS:本人不是大神,寫部落格只是為了增強記憶

Spring 基於註解配置

基於註解的配置 從 Spring 2.5 開始就可以使用註解來配置依賴注入。而不是採用 XML 來描述一個 bean 連線,你可以使用相關類,方法或欄位宣告的註解,將 bean 配置移動到元件類本身。 在 XML 注入之前進行註解注入,因此後者的配置將通過兩種方式的屬性連

JavaEE--spring-基於註解的IOC注入配置

下面我來介紹一下另一種使用在Spring框架下的IOC注入方式:基於註解的IOC.它是通過配置註解來部分或全部取代xml配置檔案.作用與xml是一樣的.一.IOC註解演示1.建立專案.引入Jar包2.建立配置檔案 bean.xml引入約束.<?xml version="

Spring——基於註解配置

Spring註解配置 從 Spring 2.5 開始就可以使用註解來配置依賴注入。使用註解的方式使我們無需在XML中配置一個Bean引用,更加簡單和方便。 註解配置預設情況下在Spring中是關閉的,我們需要在配置檔案中使用<context:annot

Spring基於註解的方式配置bean的例項

  前邊我們講過了基於配置檔案建立bean例項的另外一種方式:即使用FacctoryBean的實現類來建立配置檔案中bean的例項。下邊我們講一講使用非常頻繁的基於註解的方式來建立bean的例項。   1.註解配置bean的例項   ① Spring框架可以從classpa

Spring基於註解的快取配置--web應用例項

現在介紹一下如何在基於註解springMVC的web應用中使用註解快取,其實很簡單,就是將springMVC配置檔案與快取註解檔案一起宣告到context中就OK了。 下面我就來構建一個基於spring註解小型的web應用,這裡我使用EHCache來作為快取方案。