天天看點

Spring自動裝配和注解配置

前面已經學會如何使用的<bean>元素來聲明bean和注入<bean>,通過使用在XML配置檔案<constructor-arg>和<property>元素。

Spring容器可以自動裝配互相協作bean之間的關系,這有助于減少對XML配置,而無需編寫一個大的基于Spring應用程式的較多的<constructor-arg>和<property>元素。

自動裝配模式:

有下列自動裝配模式,可用于訓示Spring容器使用自動裝配依賴注入。使用<bean/>元素的autowire屬性為一個bean定義中指定自動裝配模式。

模式 描述
no This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its typematches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
constructor Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

可以使用類型和constructor自動裝配模式來連接配接數組和其他類型化的集合。

自動裝配的局限性:

自動裝配最好效果是它始終在一個項目中使用。如果自動裝配不一般的使用,它可能會被混淆為開發人員可以使用它來連接配接隻有一個或兩個bean定義。不過,自動裝配可以顯著減少需要指定屬性或構造器參數,但你應該使用它們之前考慮自動裝配的局限性和缺點。

限制
壓倒一切的可能性 可以使用<constructor-arg>和<property>設定總是覆寫自動裝配還指定依賴關系。
原始資料類型 不能自動裝配所謂的簡單類型包括基本類型,字元串和類。
混亂的本質 自動裝配比顯式裝配确切的少,是以如果可能的話可以使用顯式的連接配接。

從Spring2.5開始就有可能使用注釋來配置依賴注入。而是采用XML來描述一個bean接線,你可以使用注解的相關類,方法或字段聲明将bean配置到元件類本身。

注釋注入在XML注入之前進行,是以後者的配置将覆寫前者通過兩種方式連接配接的屬性。

注釋接線預設情況下不開啟在Spring容器。是以,我們才可以使用基于注解的接線,我們将需要啟用它在我們的Spring配置檔案。是以,考慮到已在下列情況下,配置檔案要使用的任何注釋在Spring應用程式。

<?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-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<!-- bean definitions go here -->

</beans>

當<context:annotation-config/>配置後,您就可以開始注釋代碼表明,Spring自動連線的值到屬性,方法和構造函數。讓我們來看看幾個重要的注解,以了解它們是如何工作的:

S.N. 注釋與說明
1

@Required

@Required注釋适用于bean屬性的setter方法。

2

@Autowired

@Autowired 注釋可以應用到bean屬性的setter方法,非setter方法,構造函數和屬性。

3

@Qualifier

@ Autowired随着@ Qualifier注釋可以用來通過指定确切的bean将有線,除去混亂。

4

JSR-250 Annotations

Spring支援JSR-250的基礎的注解,其中包括了@Resource,@PostConstruct和@PreDestroy注解。

原文釋出時間為:2018-10-23

本文來自雲栖社群合作夥伴“

Java雜記

”,了解相關資訊可以關注“

”。