1.依賴注入方法
手動裝配和自動裝配
2.手動裝配
2.1 基于xml裝配
2.1.1 構造方法
<!-- 構造方法注入<constructor-arg>name:參數名type:類型value: --> <bean id="user" class="g_xml.constructor.User"><constructor-arg name="id" type="java.lang.Integer" value="11"></constructor-arg><constructor-arg name="username" type="java.lang.String" value="張三"></constructor-arg><constructor-arg name="age" type="java.lang.Integer" value="10"></constructor-arg> </bean>
?
2.1.2 setter方法
<bean id="addr" class="g_xml.setter.Address" ><property name="addr" value="上海浦東"></property><property name="tel" value="138234324"></property> </bean> <bean id="user" class="g_xml.setter.User"><property name="id" value="1"></property><property name="username" value="張三"></property><property name="age" value="12"></property><property name="homeAddr" ref="addr"></property><property name="companryAddr" ref="addr"></property> </bean>
2.1.3 p命名空間
對setter方法注入進行簡化,替換<property>為:
但是需要加入schame命名空間
2.1.4 spEL
對<property>進行了統一編程,所有的內容都是用value
<property name="" value="#{EL表達式}">
EL:
#{123}
#{"hello"}
#{beanId} :另一個bean的引用
#{beanId.propName}
#{beanId.toString()}
#{T(類).靜態方法|字段}
2.1.5 集合注入
?
<bean id="users" class="g_xml.collections.Users"><property name="strArr"><array><value>戰三</value><value>李四</value><value>王五</value></array></property><property name="list"><list><value>111</value><value>222</value><value>333</value></list></property><property name="set"><set><value>set1</value><value>set2</value><value>set3</value></set></property><property name="map"><map><entry key="key1" value="value1"></entry><entry key="key2" value="value2"></entry></map></property><property name="properties"><props><prop key="k1">value1</prop><prop key="k2">value2</prop></props></property> </bean>
?
2.2 基于注解
? 注解就是一個類,使用@注解名稱,取代xml配置
2.2.1 @Component? == <bean id="" class="">
? @Component("id")
? 使用注解之前,必須添加命名空間,讓spring掃描帶有注解的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:context="http://www.springframework.org/schema/context"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.xsd"><!-- bean definitions here 配置所需要創建的實例對象,放入spring容器中--><!--<bean id="userService" class="a_IoC.UserServiceImp"></bean>--><context:component-scan base-package="h_annotation"></context:component-scan> </beans>
?
2.2.2 在web開發中,提供了三個Component衍生出的注解
@Repository? DAO層
@Service? ? ? ?Service層
@Controller? ?Web層
2.2.3 依賴注入? (可以給私有屬性注入,也可以給setter方法注入)
普通值:@Value()
引用值:
方式1:按照類型注入-->@Autowired
方式2:按照名稱注入 -->
@Autowired
@Qualifier("名稱")
方式2:按照名稱注入 -->
@Resource("名稱")?
?