Spring的自动装载模式

在Spring的.xml配置文件中,bean有五种autowire模式:byName,byType,constructor,autodetect,no;

1 byName:这个很简单,直接按照名字进行查找

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

 

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

2. byType:按照类型进行查找

 

 <bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl"></bean>	
 <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype" autowire="byType"></bean>

3.constructor:直接根据构造函数进行匹配

4.autodetect:先按constructor匹配,再按byType匹配
5 no:不用任何模式进行匹配,这个也是默认的匹配模式

注:

      如果所有的bean都用同一种,可以使用beans的属性:default-autowire

<!--EndFragment-->

你可能感兴趣的:(DAO,spring,bean,xml,prototype)