spring自动装配:简化spring配置文件
autowire:根据属性去查找相应的bean,如果有,则装配上去
autowire="byName" (通过名称) autowire="byType"(通过类型)autowire="constructor"(通过构造器)
package impl;
import service.UserService;
import dao.UserDao;
public class UserServiceImpl implements UserService {
//实现了service和dao的解耦
private UserDao userDao = null;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
beans.xml
<bean id="userDao" class = "impl.OracleDaoImpl"/>
<bean id="service" class = "impl.UserServiceImpl" autowire="byName"/>//userDao对应的是UserServiceImpl中的属性名称。
还有另外一种设置方法:配置全局的自动装配类型
<?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.xsd" default-autowire="byName">
autowire="byType"(通过类型)建议慎用
<bean id="service" class = "impl.UserServiceImpl" autowire="byType"/>//但是同一种类型的bean只能有1个。
autowire="constructor"(通过构造器)当通过构造器实例化bean的时候
使用bytype的方式装配构造方法
public class UserServiceImpl implements UserService {
//实现了service和dao的解耦
private UserDao userDao = null;
// public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
// }
public UserServiceImpl(UserDao userDao) {
super();
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
<bean id="userDao" class = "impl.UserDaoImpl"/>
<bean id="service" class = "impl.UserServiceImpl" autowire="constructor"/>