Sping--自动装配(byname, bytype)

UserDAOImpl.java:

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;
	}

}

UserService.java:

package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

public class UserService {	
	private UserDAO userDAO;  
	public void add(User user) {
		userDAO.save(user);
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}

UserServiceTest.java:

package com.bjsxt.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.User;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {
	@Test
	public void testAdd() throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");	
		UserService service = (UserService)ctx.getBean("userService");		
		System.out.println(service.getUserDAO());		
	}
}

bean.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>
	
  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byName">
  </bean>
  

</beans>

结果:  daoId=1

bean.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="userDAO2" class="com.bjsxt.dao.impl.UserDAOImpl">
  	<property name="daoId" value="2"></property>
  </bean>	
  <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType">
  </bean>
</beans>

结果: daoId=2

 

 

  

  

posted @ 2016-05-03 09:33  wujixing909  阅读(298)  评论(0编辑  收藏  举报