目录
一、概念(不需要添加set方法)
@Autowired:根据属性类型进行自动装配
@Qualifier:根据名称进行注入,与@Autowired 一起使用
@Resource:可以根据类型注入,可以根据名称注入
@Value:注入普通类型属性
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
二、注入对象属性
@Autowired和@Qualifier
举例
UserDaoImpl1
@Repository
public class UserDaoImpl1 implements UserDao {
@Override
public void add() {
System.out.println("dao add1...........");
}
}
UserDaoImpl2
@Repository
public class UserDaoImpl2 implements UserDao {
@Override
public void add() {
System.out.println("dao add2...........");
}
}
Service
@Service
public class UserService {
@Autowired
// @Qualifier(value = "userDaoImpl1")
private UserDao userDao;
public void add(){
System.out.println("service add........");
userDao.add();
}
}
配置文件
<context:component-scan base-package="com.atguigu.spring5"></context:component-scan>
测试
@Test
public void testService(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
结果报错
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.atguigu.spring5.dao.UserDao' available: expected single matching bean but found 2: userDaoImpl1,userDaoImpl2
原因
UserDaoImpl1与UserDaoImpl2实现一个接口,属于一个类型,不能辨别。
在UserService中添加
@Qualifier(value = "userDaoImpl1")
结果
@Resource
@Service
public class UserService {
@Resource(name="userDaoImpl1")
private UserDao userDao;
public void add(){
System.out.println("service add........");
userDao.add();
}
}
三、注入普通类型属性
@Value
@Service
public class UserService {
@Resource(name="userDaoImpl1")
private UserDao userDao;
@Value(value = "abc")
private String name;
@Value(value ="123")
private int age;
public void add(){
System.out.println("service add........"+name+age);
userDao.add();
}
}