Spring再接触 自动装配
Posted Blueburble
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring再接触 自动装配相关的知识,希望对你有一定的参考价值。
UserDaoImpl
package com.bjsxt.dao.impl; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserDAOImpl implements UserDAO { private int daoId; public int getDaoId() { return daoId; } public void setDaoId(int daoId) { this.daoId = daoId; } public void save(User user) { //Hibernate //JDBC //XML //NetWork System.out.println("user saved!"); } @Override public String toString() { return "daoId=" + daoId; } }
beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.5.xsd" > <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl"> <property name="daoId" value="1"></property> </bean> <bean name="userDAO2" class="com.bjsxt.dao.impl.UserDAOImpl"> <property name="daoId" value="2"></property> </bean> //default是指在表头指定default 然后这里设置为default就可以按照表头指定的来进行自动装配 <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType"> //按照name的话就会自动匹配Userdao 按照类型只能有一个属性才行 </bean> </beans>
testadd
@Test public void testAdd() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); UserService service = (UserService)ctx.getBean("userService"); System.out.println(service.getUserDAO()); }
以上是关于Spring再接触 自动装配的主要内容,如果未能解决你的问题,请参考以下文章