Spring 三種裝配bean的方式
阿新 • • 發佈:2018-12-13
Spring有如下三種裝配bean的方法
- 在XML中進行顯式配置
- 在Java中進行顯式配置
- 隱式的bean發現機制和自動裝配
顯示配置
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--使用bean標籤去申明bean--> <bean id="waiter" class="xyz.mrwood.study.spring.example.Waiter" /> <!--可以保用p標籤來注入依賴的bean--> <bean id="store" class="xyz.mrwood.study.spring.example.Store" p:waiter-ref="waiter" /> </beans>
在JAVA中顯示配置
要通過@Configuration與@Bean搭配來完成
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BeanConfig { /** * 申明bean * @return */ @Bean public Waiter waiter() { return new Waiter(); } @Bean public Store store() { Store store = new Store(); store.setWaiter(waiter()); //通過呼叫bean的方法來注入 return store; } }
隱式配置
@Component:標識Bean,可被自動掃描發現
@Configuration+ @ComponentScan(basepackages=”main”) : @Configuration可以指定某個類為配置類,而@ComponentScan可以指定要掃描元件的範圍,不設定引數預設掃描當前類的包以及子包。如果設定會掃描指定的類。
上述也可以換成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:component-scan base-package="*.*.*" /> </beans>
@Autowired:自動裝配,查詢容器中滿足條件的Bean,注入。
總結:
1、spring中所有bean都會有一個ID,我們通過@Component設定的,自動掃描時會以類名首字母小寫為ID。如果想要自定義就要設定@Component的引數
2、@ComponentScan預設是掃描當前包以及子包。如果想設定其它包或者多個包,可以通過設定該註解的basePackages。但是這種是以字串形式不利於重構。可以使用另外一個屬性backPackageClasses指定某個類(開發中常用標記介面),然後spring會掃描這個類下面的包與子包。
3、可以使用java規範的@Named替換@Component,也可以使用java規範的@Inject去替換@Autowired
4、@Bean註解的bean的ID預設是方法名,如果要指定名稱,可以通過name屬性來設定