1.在XML中顯式配置java
2.在Java中進行顯式配置spring
3.隱士的bean發現機制和自動裝配ide
1.在須要裝配到其餘bean中的類中加入@Component註解ui
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"; @Override public void play() { System.out.println("Playing " + titil + " by " + artist); } }
2.開啓組件掃描this
i.使用java配置開啓spa
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開啓code
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://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注入component
i.在屬性上直接注入xml
ii.在構造方法上注入blog
iii.在Set方法上注入
package study.spring.configure.auto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CDPleayer { @Autowired private CompactDisc cd; public CompactDisc getCd() { return cd; } /* * 不一樣的注入方法 * 1. set方法注入 * 2. 構造器注入 * 3. 屬性上直接注入 * * @Autowired與@Inject相似 */ @Autowired public 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配置。