spring註入對象類型的屬性
阿新 • • 發佈:2018-04-01
ops 16px dao beans oot 英語 value 類屬性 color
<!-- name的值是 UserService類屬性的值 ref是UserDao配置的ID的值-->
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.example.propetys.UserDao"></bean>
一.1.創建service類和Dao類
(1)在service中得到dao對象
2.具體實現過程
(1)在service裏邊把dao作為類型屬性
(2)生成dao類型屬性的set方法
public class UserDao { public void add(){ System.out.println("dao--------------"); } }
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add(){
System.out.println("service--------------");
userDao.add();
}
}
3.xml配置:
<bean id="userService" class="com.example.propetys.UserService"><!-- name的值是 UserService類屬性的值 ref是UserDao配置的ID的值-->
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.example.propetys.UserDao"></bean>
二:P名稱空間註入
1.建一個類:
public class Person { private String pname; public void setPname(String pname) { this.pname = pname; } public void test(){ System.out.println("asdhjcbsdj"+pname); } }
2.xml文件<beans>下
xmlns:p="http://www.springframework.org/schema/p"
<bean id="person" class="com.example.propetys.Person" p:pname="lucy"></bean>
三.註入復雜類型屬性
1.數組
2.list集合
3.map集合
4.properties類型
(1)建一個類
import java.util.List; import java.util.Map; import java.util.Properties; public class Person { private String pname; public void setPname(String pname) { this.pname = pname; } private String[] arrs; private List<String> list; private Map<String, String> map; private Properties properties; public void setArrs(String[] arrs) { this.arrs = arrs; } public void setList(List<String> list) { this.list = list; } public void setMap(Map<String, String> map) { this.map = map; } public void setProperties(Properties properties) { this.properties = properties; } public void test(){ System.out.println("arrs:"+arrs); System.out.println("list:"+list); System.out.println("map:"+map); System.out.println("properties:"+properties); } }
(2)配置xml文件
<bean id="person" class="com.example.propetys.Person" >
<!-- 數組 -->
<property name="arrs">
<list>
<value>數學</value>
<value>語文</value>
<value>歷史</value>
<value>英語</value>
</list>
</property>
<!-- list -->
<property name="list">
<list>
<value>c/c++</value>
<value>java</value>
</list>
</property>
<!-- map -->
<property name="map">
<map>
<entry key="a" value="圖書館"></entry>
<entry key="b" value="教學樓"></entry>
<entry key="c" value="宿舍"></entry>
</map>
</property>
<!-- properties -->
<property name="properties">
<props>
<prop key="driverclass">com.mysql.jdbc.Driver</prop>
<prop key="username">root</prop>
</props>
</property>
</bean>
spring註入對象類型的屬性