Spring_spring自动装配置注解(@Autowired)指定要装配置的参数(@Qualifier)
原创
©著作权归作者所有:来自51CTO博客作者wx62dfdc6aea345的原创作品,请联系作者获取转载授权,否则将追究法律责任
@Autowired
a>默认按类型by type
b>如果想用byName,使用Qulifler
c>写在private field(第三种注入形式)(不建议,破封装)
d>如果写在set上,@qualifier需要写在参数上
导入spring注解配置
xmlns:context="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="userDaoImpl" class="com.bjsxd.dao.impl.UserDaoImpl">
</bean>
<bean id="userDaoImpl2" class="com.bjsxd.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.bjsxd.service.UserService">
</bean>
</beans>
package com.bjsxd.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.bjsxd.dao.UserDao;
import com.bjsxd.model.User;
public class UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
@Autowired//自动装配
public void setUserDao(@Qualifier("userDaoImpl")UserDao userDao) {//指定要使用的的bean的ID注入
this.userDao = userDao;
}
public void add(User user) {
userDao.save(user);
}
}