定义一个接口
public interface HelloService {
void sayHello();
}
实现HelloService接口
@Service
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("hello");
}
}
@Service
public class Hello2ServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("hello");
}
}
@Resource注解
调用HelloService接口
什么都不指定的情况下默认按照name进行匹配。
@Resource
private HelloService helloService;
运行代码结果如下:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘helloController’: Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type ‘com.example.wechat.service.HelloService’
available: expected single matching bean but found 2:
hello2ServiceImpl,helloServiceImpl
指定name:
@Resource(name = "helloServiceImpl")
private HelloService helloService;
@Resource(name = "hello2ServiceImpl")
private HelloService helloService;
指定type:
@Resource(type = HelloServiceImpl.class)
private HelloService helloService;
@Resource(type = Hello2ServiceImpl.class)
private HelloService helloService;
同时指定name和type
@Resource(name = "hello2ServiceImpl", type = Hello2ServiceImpl.class)
private HelloService helloService;
@Autowired注解
直接爆红。爆红提示如下:
根据提示代码可以改成下图所示:加上Qualifier()注解,指定需要的bean。
总结:一个类型有多个bean值的时候。使用@Autowired时需要与@Qualifier()注解一起使用。使用@Resource,我们可以指定他的name或者type或者同时指定name和type.这样才不会有问题。@Resource默认是按照byName进行的。@Autowired按照byType注入。@Autowired是Spring提供的。@Resource是J2EE提供的。两个都可以写在字段上就不需要写setter方法了。@Autowired还可以写在非 setter 方法,构造函数和属性上。