spring框架為我們提供了三種注入方式,分別是set注入,構造方法注入,接口注入。接口注入不作要求,下面介紹前兩種方式。
1,set注入
采用屬性的set方法進(jìn)行初始化,就成為set注入。
1)給普通字符類(lèi)型賦值。
- public class User{
- privateString username;
-
- publicString getUsername() {
- returnusername;
- }
- publicvoid setUsername(String username) {
- this.username= username;
- }
- }
我們只需要提供屬性的set方法,然后去屬性文件中去配置好讓框架能夠找到applicationContext.xml文件的beans標簽。標簽beans中添加bean標簽,指定id,class值,id值不做要求,class值為對象所在的完整路徑。bean標簽再添加property 標簽,要求,name值與User類(lèi)中對應的屬性名稱(chēng)一致。value值就是我們要給User類(lèi)中的username屬性賦的值。
- <bean id="userAction"class="com.lsz.spring.action.User" >
- <span style="white-space:pre"> </span><property name="username" value="admin"></property>
- </bean>
2)給對象賦值
同樣提供對象的set方法
- public class User{
- private UserService userservice;
- public UserServicegetUserservice() {
- returnuser;
- }
- public void setUserservice(UserService userservice){
- this.userservice= userservice;
- }
- }
配置文件中要增加UserService的bean標簽聲明及User對象對UserService引用。
-
- <bean id="userService" class="com.lsz.spring.service.UserService"></bean>
-
- <bean id="userAction"class="com.lsz.spring.action.User" >
- <property name="userservice" ref="userService"></property>
- </bean>
這樣配置,框架就會(huì )將UserService對象注入到User類(lèi)中。
3)給list集合賦值
同樣提供set方法
- public class User{
- privateList<String> username;
- publicList<String> getUsername() {
- returnusername;
- }
- publicvoid setUsername(List<String> username) {
- this.username= username;
- }
- }
- <bean id="userAction"class="com.lsz.spring.action.User" >
- <propertynamepropertyname="username">
- <list>
- <value>zhang,san</value>
- <value>lisi</value>
- <value>wangwu</value>
- </list>
- </property>
- </bean>
4)給屬性文件中的字段賦值
- public class User{
- privateProperties props ;
- publicProperties getProps() {
- returnprops;
- }
- publicvoid setProps(Properties props) {
- this.props= props;
- }
- }
- <bean>
- <propertynamepropertyname="props">
- <props>
- <propkeypropkey="url">jdbc:oracle:thin:@localhost:orl</prop>
- <propkeypropkey="driverName">oracle.jdbc.driver.OracleDriver</prop>
- <propkeypropkey="username">scott</prop>
- <propkeypropkey="password">tiger</prop>
- </props>
- </property>
- </bean>
<prop>標簽中的key值是.properties屬性文件中的名稱(chēng)
注意:
無(wú)論給什么賦值,配置文件中<property>標簽的name屬性值一定是和對象中名稱(chēng)一致。
2構造方法注入
1)構造方法一個(gè)參數
- public class User{
- privateString usercode;
- publicUser(String usercode) {
- this.usercode=usercode;
- }
- }
- <bean id="userAction"class="com.lsz.spring.action.User">
- <constructor-argvalueconstructor-argvalue="admin"></constructor-arg>
- </bean>
2)構造函數有兩個(gè)參數時(shí)
當參數為非字符串類(lèi)型時(shí),在配置文件中需要制定類(lèi)型,如果不指定類(lèi)型一律按照字符串類(lèi)型賦值。
當參數類(lèi)型不一致時(shí),框架是按照字符串的類(lèi)型進(jìn)行查找的,因此需要在配置文件中制定是參數的位置
- <constructor-argvalueconstructor-argvalue="admin"index="0"></constructor-arg>
- <constructor-argvalueconstructor-argvalue="23" type="int"index="1"></constructor-arg>
-
這樣制定,就是構造函數中,第一個(gè)參數為string類(lèi)型,第二個(gè)參數為int類(lèi)型
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。