Spring依賴注入,自動掃描元件,自動裝配,註解注入
阿新 • • 發佈:2019-02-11
Spring 依賴注入
Spring框架中,依賴注入(DI)的設計模式是用來定義物件彼此間的依賴。它主要有兩種型別:- Setter方法注入
- 構造器注入
<!-- 建立一個 Spring bean 的配置檔案,並在這裡宣告所有的Java物件的依賴。 --> <bean id="gradebeen" class="com.hst.spring.demo.Grade" init-method="init"> <property name="name" value="java班"></property> </bean> <!-- set 設值注入 property ,been中必須要有set方法 --> <bean id="student" class="com.hst.spring.demo.Student"> <property name="name" value="小明"></property> <property name="number" value="1001"></property> <property name="grade" ref="gradebeen"></property> </bean> <!-- 構造方法 constructor,必須要有預設的構造方法 index下標 value屬性賦值 ref物件賦值 --> <bean id="user" class="com.hst.spring.demo.User"> <constructor-arg index="0" value="teacher" type="String" /> <constructor-arg index="1" ref="gradebeen"></constructor-arg> </bean>
自動裝配
在Spring中,支援 5 自動裝配模式。- no – 預設情況下,自動配置是通過“ref”屬性手動設定
- byName – 根據屬性名稱自動裝配。如果一個bean的名稱和其他bean屬性的名稱是一樣的,將會自裝配它。
- byType – 按資料型別自動裝配。如果一個bean的資料型別是用其它bean屬性的資料型別,相容並自動裝配它。
- constructor – 在建構函式引數的byType方式。
- autodetect – 如果找到預設的建構函式,使用“自動裝配用構造”; 否則,使用“按型別自動裝配”。
<!-- 建立一個 Spring bean 的配置檔案,並在這裡宣告所有的Java物件的依賴。 --> <bean id="gradebeen" class="com.hst.spring.demo.Grade" init-method="init"> <property name="name" value="java班"></property> </bean> <!-- set 設值注入 property ,been中必須要有set方法 --> <bean id="student" class="com.hst.spring.demo.Student"> <property name="name" value="小明"></property> <property name="number" value="1001"></property> <property name="grade" ref="gradebeen"></property> --------ref </bean>
2.byName 例項
<bean id="customer" class="com.hst.spring.Student" autowire="byName" />
<bean id="person" class="com.hst.spring.Person" />
default-autowire="byName"5.autodetect例項
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
default-autowire="autodetect">
註解注入,自動掃描元件
<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-2.5.xsd
http://www.springframework.org/schema/context ---------
http://www.springframework.org/schema/context/spring-context.xsd"> ---------
<context:component-scan base-package="com.hst.integraimanager.server.impl" /> --------
</beans>
* 自動元件掃描
* @Component – 指示自動掃描元件。
@Repository – 表示在持久層DAO元件。
@Service – 表示在業務層服務元件。
@Controller – 表示在表示層控制器元件。
@Autowired 註釋,它可以對類成員變數、方法及建構函式進行標註,完成自動裝配的工作。
通過 @Autowired的使用來消除 set ,get方法。