spring框架之 IoC和DI(二)
九、依賴注入
9、1 屬性依賴注入
- 依賴注入方式:手動裝配 和 自動裝配
手動裝配:一般進行配置資訊都採用手動
① 基於xml裝配:構造方法、setter方法 、 p標籤注入
② 基於註解裝配:@autowrired @resource
自動裝配:
autowire="byName"
byType:按型別裝配 byName:按名稱裝配 constructor:構造裝配, auto: 不確定裝配。
9、2 構造方法
Book.java
public Book(String name, String author, double price) { super(); this.name = name; this.author = author; this.price = price; }
Student.java
public Student(String name, Book book) {
super();
this.name = name;
this.book = book;
}
xml
index :引數的索引號,從0開始 。如果只有索引,匹配到了多個構造方法時,預設使用第一個。
type :確定引數型別(下標獲取可以加上這個屬性 ,型別為java.lang.String……)
<!-- 方式一:通過下標獲取 --> <bean id="book" class="com.tf.constructor.Book"> <constructor-arg index="0" value="最好的我們"></constructor-arg> <constructor-arg index="1" value="八月長安"></constructor-arg> <constructor-arg index="2" value="123"></constructor-arg> </bean> <!-- 方式二:通過有參構造的name , 普通欄位用value 引用資料型別 ref --> <bean id="book1" class="com.tf.constructor.Book"> <constructor-arg name="name" value="何以笙簫默"></constructor-arg> <constructor-arg name="author" value="饒雪漫"></constructor-arg> <constructor-arg name="price" value="121"></constructor-arg> </bean> <!-- 建立Student物件 --> <bean id="stu" class="com.tf.constructor.Student"> <constructor-arg name="name" value="蘇蘇"></constructor-arg> <constructor-arg name="book" ref="book"></constructor-arg> </bean>
9、3 setter方法
呼叫setter方法注入屬性值 setName() setAuthor() setPrice()( 必須需要無參構造)
<bean id="b" class="com.tf.setter.Book"> <!-- 必須需要無參構造 呼叫setter方法注入屬性值 setName() setAuthor() setPrice() --> <property name="name" value="獨孤天天"></property> <property name="author" value="CC"></property> <property name="price" value="233"></property> </bean> <bean id="s" class="com.tf.setter.Student"> <property name="name" value="喵喵"></property> <property name="book" ref="b"></property> </bean>
9、4 p命令空間注入(瞭解)
1、對“setter方法注入”進行簡化,替換<property name="屬性名">,而是在
<bean p:屬性名="普通值" p:屬性名-ref="引用值">
2、p名稱空間使用前提,必須新增名稱空間
3、程式碼:
<!-- p標籤注入 -->
<bean id="b" class="com.tf.p.Book" p:name="笑死" p:author="李希" p:price="100"></bean>
<bean id="stu" class="com.tf.p.Student" p:name="天天" p:book-ref="b"></bean>
9、5 集合注入
MyCollection.java
private String array[];
private List<String> list;
private Set<String> set;
private Map<String,Object> map;
private Properties properties;
private List<Book> book;
spring-di.xml
<!-- 各種集合的注入 -->
<bean id="b" class="com.tf.collection.Book">
<property name="name" value="十萬個為啥"></property>
<property name="author" value="大俠"></property>
<property name="price" value="233"></property>
</bean>
<bean id="myCollections" class="com.tf.collection.MyCollection">
<!-- 陣列 -->
<property name="array">
<array>
<value>足球</value>
<value>籃球</value>
<value>排球</value>
</array>
</property>
<!-- list -->
<property name="list">
<list>
<value>java</value>
<value>python</value>
</list>
</property>
<!-- List<Book> -->
<property name="book">
<list>
<ref bean="b"></ref>
</list>
</property>
<!-- set -->
<property name="set">
<set>
<value>數學</value>
<value>英語</value>
</set>
</property>
<property name="map">
<map>
<entry>
<key><value>name</value></key>
<value>李四</value>
</entry>
<entry>
<key><value>age</value></key>
<value>12</value>
</entry>
</map>
</property>
<!-- properties型別 -->
<property name="properties">
<props>
<prop key="dirverClassName">
com.mysql.jdbc.Driver
</prop>
<prop key="url">
jdbc:mysql///mydb
</prop>
</props>
</property>
</bean>
十、常用註解(重點)
面試題:請說出spring常用的註解有哪些?
- 註解:就是一個類,使用@註解名稱
- 開發中:使用註解 取代 xml配置檔案。
①: @Component取代<bean class="">
@Component("id") 取代 <bean id="" class="">
②:web開發,提供3個@Component註解衍生註解(功能一樣)取代<bean class="">
@Repository :dao層
@Service:service層
@Controller:web層
③:依賴注入,給私有欄位設定,也可以給setter方法設定
方式1:按照【型別】注入
@Autowired(spring提供的)
private BookDao bookDao;
方式2:按照【名稱】注入2
@Resource( name="名稱") (jdk提供的,jdk>1.6版本)
@Resource( name="bookDao")
private BookDao bookDao; //spring容器中找name為bookDao
方式3:按照型別注入(autowired)時,如果有兩個匹配結果,會報錯
可以使用如下解決方案:
@Qualifier("userServiceImpl2")
注意:@Qualifier不能當獨使用,一般配合autowired使用
④:生命週期
初始化:@PostConstruct
銷燬: @PreDestroy
⑤:作用域 (類前)
@Scope("prototype") 多例
注意:
註解使用前提,匯入aop的包,新增名稱空間,讓spring掃描含有註解類
spring-aop-4.3.5.RELEASE.jar
在配置檔案中新增context標籤:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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節點來掃描有註解的包 及其子包 -->
<context:component-scan base-package="com.tf.annotation"></context:component-scan>
</beans>
⑥:普通屬性有關的註解
@value 注入屬性值
1、加在成員變數上:通過反射的Field賦值(破壞物件的封裝性)
@Value("梅梅") private String name; |
2、加在set方法上:通過set方法賦值
@Value("tom") public void setName(String name) { this.name = name; } |
@Value直接讀取properties檔案中的內容
- 配置檔案
<!-- 掃描properties檔案 --> <context:property-placeholder location="classpath:dbinfo.properties"/> <!—掃描一次--> <!-- 掃描帶有註解的包 指定要掃描的包 --> <context:component-scan base-package="com.itqf"></context:component-scan> |
3、在類中使用@value註解讀取配置檔案中的內容
@value(“${properties配置檔案中的key}”)
@Value("${jdbc.driver}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; |
十一、Spring 整合Junit4測試
spring整合junit,為我們提供了方便的測試方式
1、導包:
spring-test-4.3.5.RELEASE.jar
junit4的包
2、建立測試類
//建立容器 @RunWith(SpringJUnit4ClassRunner.class) //指定建立容器時使用哪個配置檔案 @ContextConfiguration("classpath:applicationContext.xml") public class RunWithTest { //將名為user的物件注入到u變數中 @Resource(name="person") private Person p; @Test public void testCreatePerson(){ System.out.println(p); } } |
十二、基於xml的自動裝配(不建議使用,不容易閱讀)
自動找到注入的物件:
autowire="byType" 按照型別
autowire="byName" 按照名字
autowire="default" 預設不裝配
spring-di2.xml 程式碼:
<bean id="b" class="com.tf.setter.Book">
<property name="name" value="獨孤九劍"></property>
<property name="author" value="見著"></property>
<property name="price" value="233"></property>
</bean>
<bean id="s" class="com.tf.setter.Student" autowire="byType">
<property name="name" value="笑死"></property>
<property name="book" ref="b"></property>
</bean>
測試:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/tf/setter/spring-di2.xml")
public class TestAuto {
@Resource
private Student s;
@Test
public void test1(){
System.out.println(s);
}
}