日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring-基于注解的配置[02自动装载bean]

發布時間:2025/3/21 javascript 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring-基于注解的配置[02自动装载bean] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  • 使用Autowired進行自動注入
    • 實例
  • 使用Auotwired的required屬性
    • 實例
  • 使用Qualifier指定注入Bean的名稱
    • 實例
  • 對類方法進行標注
    • 實例
    • 小結
  • 對集合類進行標注
    • 實例
  • 對延遲依賴注入的支持
    • 實例
  • 對標準注解的支持
    • 實例
    • 小結

使用@Autowired進行自動注入

Spring通過@Autowired注解實現Bean的依賴注入。

@Autowired默認按照類型(byType)匹配的方式在容器中查找匹配的Bean,當且僅有一個匹配的Bean時,Spring將其注入@Autowired標注的變量中。

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class Pilot {@Autowiredprivate Plane plane;public void drivePlane() {plane.fly();} }

實例

POJO類

package com.xgj.ioc.configuration;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class Pilot {@Autowiredprivate Plane plane;public void drivePlane() {plane.fly();} }

@Component注解將Pilot標注為一個Bean,Spring會掃描加載并實例化該Bean。

通過@Autowired注入plan的Bean。


POJO類

package com.xgj.ioc.configuration;import org.springframework.stereotype.Component;@Component public class Plane {private String brand;private String color;private int speed;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public void introduce() {System.out.println("Plane information【 brand:" + brand + ",color:"+ color + ",speed:" + speed);}public void fly() {System.out.println("Plane begins to fly");} }

配置文件

<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- (1)聲明Context命名空間以及Schema文件 (2)掃描類包以及應用注解定義的bean --><context:component-scan base-package="com.xgj.ioc.configuration"/></beans>

測試類

package com.xgj.ioc.configuration;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class ConfigBeanTest {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/ioc/configuration/beans.xml");Pilot pilot = ctx.getBean("pilot", Pilot.class);pilot.drivePlane();Plane plane = ctx.getBean("plane", Plane.class);plane.setBrand("A380");plane.setColor("White");plane.setSpeed(800);plane.introduce();} }

運行結果:


使用@Auotwired的required屬性

如果容器中沒有一個和標注變量類型匹配的Bean,那么Spring啟動的時候會報NoSuchBeanDefinitionException異常。 如果希望Spring及時找不到匹配的Bean完成注入也不要拋出異常,那么就可以使用@Autowired(required=false)進行標注。

實例

還是以上面的例子為基礎改造下,我們知道上面的掃描包配置的為

<context:component-scan base-package="com.xgj.ioc.configuration"/>

假設在com.xgj.ioc.configuration之外的包目錄下 有個Tank類(com.xgj.ioc.inject.construct.type.Tank)

改造下Pilot類,引入Tank,設置自動注入

package com.xgj.ioc.configuration;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;import com.xgj.ioc.inject.construct.type.Tank;@Component public class Pilot {@Autowiredprivate Plane plane;@Autowiredprivate Tank tank;public void drivePlane() {plane.fly();} }

@Autowired 默認 required =true

運行測試類:

No qualifying bean of type 'com.xgj.ioc.inject.construct.type.Tank' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我們改造下@Autowired(required = false)

@Autowired(required = false) private Tank tank;

再此運行: OK


使用@Qualifier指定注入Bean的名稱

如果容器中有一個以上匹配的Bean時,則可以通過@Qualifier注解限定Bean的名稱。

假設容器中有兩個類型為Plane的Bean,一個名為plane,一個名為otherPlane. 因為@Autowired默認是按照類型匹配的方式在容器中查找,plane和otherPlane的類型都是Plane,怎么知道注入哪一個呢?

實例

我們在掃描的基類包下增加個子包 other,包下新增同名Plane類,通過@Component(“otherPlane”)指定Bean的名稱。

com.xgj.ioc.configuration.other.Plane代碼如下:

package com.xgj.ioc.configuration.other;import org.springframework.stereotype.Component;@Component("otherPlane") public class Plane {private String brand;private String color;private int speed;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public void introduce() {System.out.println("OtherPlane information【 brand:" + brand + ",color:"+ color + ",speed:" + speed);}public void fly() {System.out.println("OtherPlane begins to fly");} }

如果我們希望注入otherPlane呢?

我們來改造Pilot類

package com.xgj.ioc.configuration;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component;// 1. 引入其他子包下的Plane import com.xgj.ioc.configuration.other.Plane; import com.xgj.ioc.inject.construct.type.Tank;@Component public class Pilot {@Autowired// 2 通過@Qualifier限定Bean的名稱@Qualifier("otherPlane")private Plane plane;@Autowired(required = false)private Tank tank;public void drivePlane() {plane.fly();} }

測試類中改動的地方

記得引入 other子包下的Plane

import com.xgj.ioc.configuration.other.Plane; ..... Plane plane = ctx.getBean("otherPlane", Plane.class);

然后運行測試類:


對類方法進行標注

@Autowired可以對類成員變量以及方法的入參進行標注。

下面在類的方法上使用@Autowired注解。

實例

package com.xgj.ioc.configuration.method;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class Pilot {private Plane plane;// 自動將Plane類型傳給方法入參@Autowiredpublic void setPlane(Plane plane) {this.plane = plane;}public void drivePlane() {plane.fly();}}

如果是下面這種寫法

// 自動將名為plane的Bean傳給方法入參@Autowired@Qualifier("plane")public void setPlane(Plane plane) {this.plane = plane點內容**

如果一個方法擁有多個入參,在默認情況下,Spring將自動選擇匹配入參類型的Bean進行注入。 Spring允許對方法入參標注@Qualifier以指定注入Bean的名稱。

比如

@Autowiredpublic void setPlane(Plane plane, @Qualifier("tank") Tank tank) {this.plane = plane;}

在這種情況下,Plane的入參注入為Plane類型的Bean,而Tank的入參注入的則為名稱為tank的Bean.

實例代碼如下:

Pilot POJO類

package com.xgj.ioc.configuration.method;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class Pilot {private Plane plane;// 自動將Plane類型傳給方法入參@Autowiredpublic void setPlane(Plane plane) {this.plane = plane;}public void drivePlane() {plane.fly();} }

Plane POJO類

package com.xgj.ioc.configuration.method;import org.springframework.stereotype.Component;@Component // 通過注解標注為一個Bean,以便Spring掃描并實例化 public class Plane {public void fly() {System.out.println("Plane begins to fly");}}

配置文件

<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- (1)聲明Context命名空間以及Schema文件 (2)掃描類包以及應用注解定義的bean --><context:component-scan base-package="com.xgj.ioc.configuration.method"/></beans>

測試類

package com.xgj.ioc.configuration.method;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class ConfigMethodTest {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/ioc/configuration/method/beans.xml");Pilot pilot = ctx.getBean("pilot", Pilot.class);pilot.drivePlane();} }

運行結果

小結

一般情況下,Spring容器中大部分的Bean是單實例的,所以一般無需通過@Repository、@Service等注解的value屬性指定Bean的名稱,也無須使用@Qualifier注解按照名稱進行注入。

雖然Spring支持在屬性和方法上標注自動注入注解@Autowired,但在實際項目開發中建議采用在方法上標注@Autowired,因為這樣更加“面向對象”,也方便單元測試的編寫, 如果將注解標注在私有屬性上,則在單元測試的時候就很難用編程的辦法設置屬性值。


對集合類進行標注

如果對類中集合類的變量或者方法入參進行@Autowired標注,那么Spring會將容器中類型所有匹配的Bean都自動注入進來。

實例

接口 Plugin

package com.xgj.ioc.configuration.lstmpSupport;public interface Plugin {}

POJO

package com.xgj.ioc.configuration.lstmpSupport;import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;@Component @Order(value = 1) public class Plugin1 implements Plugin {/*** * * @Title:Plugin1* * @Description:構造函數*/public Plugin1() {super();System.out.println("Pligin1 Init");} }

POJO

package com.xgj.ioc.configuration.lstmpSupport;import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;@Component @Order(value = 2) public class Plugin2 implements Plugin {/*** * @Title:Plugin2* * @Description:構造函數* * */public Plugin2() {super();System.out.println("Pligin2 Init");}}

通過@Component標注為Bean,Spring會將 Plugin1和Plugin2這兩個Bean都注入到plugins中。 在默認情況下,這兩個bean的加載順序是不確定,在Spring4.0中可以通過@Order注解或者實現Ordered接口來決定Bean加載的順序,值越小,優先被加載。

POJO

package com.xgj.ioc.configuration.lstmpSupport;import java.util.List; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class MyComponent {private List<Plugin> plugins;private Map<String, Plugin> pluginMap;// Spring會將容器中所有類型為Plugin的Bean注入到這個變量中@Autowired(required = false)public void setPlugins(List<Plugin> plugins) {this.plugins = plugins;}// 將Plugin類型的Bean注入到Map中@Autowiredpublic void setPluginMap(Map<String, Plugin> pluginMap) {this.pluginMap = pluginMap;}/*** * * @Title: getPlugins* * @Description: 獲取Plugins* * @return* * @return: List<Plugin>*/public List<Plugin> getPlugins() {return plugins;}/*** * * @Title: getPluginMap* * @Description: 獲取Map* * @return* * @return: Map<String,Plugin>*/public Map<String, Plugin> getPluginMap() {return pluginMap;}}

Spring如果發現變量是一個List和一個Map的集合類,則它會將容器中匹配集合元素類型的所有Bean都注入進來。

private Map

<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- (1)聲明Context命名空間以及Schema文件 (2)掃描類包以及應用注解定義的bean --><context:component-scan base-package="com.xgj.ioc.configuration.lstmpSupport"/></beans>

測試類:

package com.xgj.ioc.configuration.lstmpSupport;import java.util.List; import java.util.Map; import java.util.Map.Entry;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class ListMapSupportTest {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/ioc/configuration/lstmpSupport/beans.xml");// 從容器中獲取beanMyComponent myComponent = ctx.getBean("myComponent", MyComponent.class);// 獲取Map集合Map<String, Plugin> map = myComponent.getPluginMap();// Map遍歷key和valuefor (Entry<String, Plugin> entry : map.entrySet()) {System.out.println("key:" + entry.getKey());System.out.println("value:" + entry.getValue());}// 獲取list集合List<Plugin> list = myComponent.getPlugins();// 遍歷listfor (int i = 0; i < list.size(); i++) {System.out.println("list中的元素" + i + "為" + list.get(i));}} }

運行結果:


對延遲依賴注入的支持

Spring4.0支持延遲依賴注入,即在Spring容器的時候,對已在Bean上標注了@Lazy和@Autowired注解的屬性,不會立即注入屬性值。 而是延遲到調用此屬性的時候才會注入屬性值。

對于Bean實施延遲依賴注入,要注意@Lazy注解必須同時標注在屬性及目標Bean上,二者缺一不可,否則延遲注入無效。

實例

package com.xgj.ioc.configuration.lazyLoad;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component;@Component public class Pilot {private Plane plane;// 延遲注入@Lazy@Autowired(required = false)public void setPlane(Plane plane) {this.plane = plane;}}

POJO

package com.xgj.ioc.configuration.lazyLoad;import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component;@Lazy // @Lazy 目標Bean 延遲注入 @Component // 通過注解標注為一個Bean,以便Spring掃描并實例化 public class Plane {/*** * * @Title:Plane* * @Description:無參構造函數*/public Plane() {super();System.out.println("Plan init ");}public void fly() {System.out.println("Plane begins to fly");}}

配置文件:

<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- (1)聲明Context命名空間以及Schema文件 (2)掃描類包以及應用注解定義的bean --><context:component-scan base-package="com.xgj.ioc.configuration.lazyLoad"/></beans>

測試

package com.xgj.ioc.configuration.lazyLoad;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class LazyLoadTest {public static void main(String[] args) {// 初始化容器ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/ioc/configuration/lazyLoad/beans.xml");} }

運行結果:

我們可以看到,并沒有實例化Plane這個Bean.

我們將@Lazy去掉,再次運行下

可以看到 啟動容器的時候,Plane bean已經被加載實例化了。


對標準注解的支持

Spring還支持JSR-250中定義的@Resource和JSR-330中定義的@Inject注解,這兩個標準注解和@Autowired注解的功能類似,都能對類變更及方法入參提供自動注入功能。

@Resource注解要求提供一個Bean名稱的屬性,如果屬性為空,則自動采用標注處的變量名或者方法名作為Bean的名稱。

實例

POJO

package com.xgj.ioc.configuration.standard;import javax.annotation.Resource;import org.springframework.stereotype.Component;@Component public class Pilot {private Plane plane;@Resource(name = "plane")public void setPlane(Plane plane) {this.plane = plane;}public void drivePlane() {plane.fly();}}

POJO

package com.xgj.ioc.configuration.standard;import org.springframework.stereotype.Component;@Component public class Plane {public void fly() {System.out.println("plane begins to fly");}}

配置文件

<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- (1)聲明Context命名空間以及Schema文件 (2)掃描類包以及應用注解定義的bean --><context:component-scan base-package="com.xgj.ioc.configuration.standard"/></beans>

測試類

package com.xgj.ioc.configuration.standard;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class StandardTest {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/ioc/configuration/standard/beans.xml");ctx.getBean("pilot", Pilot.class).drivePlane();} }

運行結果

小結

如果@Resource未指定plane屬性,則也可以根據屬性方法得到需要注入的Bean名稱。

@Autowired默認按照類型匹配注入bean, @Resource默認按照名稱匹配注入Bean。而@Inject和@Autowired同樣也是按照類型匹配注入Bean的,只不過它沒有required屬性。

可見不管是@Resource或者@Inject注解,其功能都沒有@Autowired豐富,因此除非有不要,大可不必在乎這兩個注解


總結

以上是生活随笔為你收集整理的Spring-基于注解的配置[02自动装载bean]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。