當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【Spring】—— 自动装配
生活随笔
收集整理的這篇文章主要介紹了
【Spring】—— 自动装配
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、Spring中裝配bean的方式
1.在XML中顯式配置
2.在Java中進行顯式配置
3.隱士的bean發現機制和自動裝配
二、自動裝配示例
1.在需要裝配到其他bean中的類中加入@Component注解
package study.spring.configure.auto;import org.springframework.stereotype.Component;/*** 第一步:將該類聲明成一個組件類,括號內的參數為組件類的id自定義名稱,也可以使用@Named.* spring會自動生成該類的bean* @author wang**/ @Component("lonelyHeartsClub") public class SgtPeppers implements CompactDisc{private String titil = "Sgt. Pepper's Lonely Hearts Club Band.";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + titil + " by " + artist);}}?
2.開啟組件掃描
i.使用java配置開啟
package study.spring.configure.auto;import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;/** 使用@ComponentScan注解開啟組件掃描,設置掃描的基礎包名* 參數basePackages* 或者basePackageClasses*/@Configuration @ComponentScan(basePackages={"study.spring.configure.auto","study.spring.configure.auto2"}) public class CDPlayerConfig {}?
ii.使用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"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="study.spring.configure.auto"></context:component-scan></beans>?
3.在注入的bean中選擇三種方法,使用@Autowired對bean注入
i.在屬性上直接注入
ii.在構造方法上注入
iii.在Set方法上注入
package study.spring.configure.auto;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class CDPleayer {@Autowiredprivate CompactDisc cd;public CompactDisc getCd() {return cd;}/** 不同的注入方法* 1. set方法注入* 2. 構造器注入* 3. 屬性上直接注入 * * @Autowired與@Inject類似*/@Autowiredpublic void setCd(CompactDisc cd) {this.cd = cd;}@Autowired(required=false)public CDPleayer(CompactDisc compactDisc) {this.cd = compactDisc;}public void play(){cd.play();} }?
注:可以在任何方法上使用@Autowired注入
三、自動注入的局限性
雖然自動注入很方便,但是自動注入需要自動創建bean實例,但是對于第三方的jar包中的類文件而言,不能直接使用注解進行聲明為組件,因此還需要xml配置。
轉載于:https://www.cnblogs.com/bopo/p/9274455.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【Spring】—— 自动装配的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [SPOJ 687]Repeats
- 下一篇: 最小生成树实验