一.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>
原文地址:https://www.cnblogs.com/xxdebug/p/8682553.html
时间: 2024-10-25 05:15:58