一、@Autowired
1、@Autowired是spring自带的注解,通过‘AutowiredAnnotationBeanPostProcessor’ 类实现的依赖注入;
2、@Autowired是根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Qualifier;
3、@Autowired有个属性为required,可以配置为false,如果配置为false之后,当没有找到相应bean的时候,系统不会抛错;
4、@Autowired可以作用在变量、setter方法、构造函数上。
a、将@autowored写在被注入的成员变量上,就不用再xml文件中配置了,在程序中去掉相应的setter和getter方法,
b、还可以写在构造方法上、setter方法上
c、@Qualifier
@Qualifier("XXX") 中的 XX是 Bean 的名称,所以 @Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。
不过需要注意的是@Autowired 可以对成员变量、方法以及构造函数进行注释,而 @Qualifier 的标注对象是成员变量、方法入参、构造函数入参
二、@Inject
1、@Inject是JSR330 (Dependency Injection for Java)中的规范,需要导入javax.inject.Inject;实现注入。
2、@Inject是根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Named;
3、@Inject可以作用在变量、setter方法、构造函数上。
a、将@Inject可以作用在变量、setter方法、构造函数上,和@Autowired一样
b、@Named
@Named("XXX") 中的 XX是 Bean 的名称,所以 @Inject和 @Named结合使用时,自动注入的策略就从 byType 转变成 byName 了。
三、@Resource
1、@Resource是JSR250规范的实现,需要导入javax.annotation实现注入。
2、@Resource是根据名称进行自动装配的,一般会指定一个name属性
3、@Resource可以作用在变量、setter方法上。
a、@Resource实例
为了方便理解,参考了一个实际的例子,大家体会一下:
(原文链接)https://blog.csdn.net/wangzuojia001/article/details/54312074/
现在有一个接口Human和两个实现类ManImpl、WomanImpl,在service层的一个bean中要引用了接口Human,这种情况处理如下:
接口Human
- package testwebapp.com.wangzuojia.service;
- public interface Human {
- public void speak();
- public void walk();
- }
实现类ManImpl
- package testwebapp.com.wangzuojia.service.impl;
- import org.springframework.stereotype.Service;
- import testwebapp.com.wangzuojia.service.Human;
- @Service
- public class ManImpl implements Human {
- public void speak() {
- System.out.println(" man speaking!");
- }
- public void walk() {
- System.out.println(" man walking!");
- }
- }
实现类WomanImpl
- package testwebapp.com.wangzuojia.service.impl;
- import org.springframework.stereotype.Service;
- import testwebapp.com.wangzuojia.service.Human;
- @Service
- public class WomanImpl implements Human {
- public void speak() {
- System.out.println(" woman speaking!");
- }
- public void walk() {
- System.out.println(" woman walking!");
- }
- }
主调类SequenceServiceImpl
- package testwebapp.com.wangzuojia.service.impl;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- import testwebapp.com.wangzuojia.dao.SequenceMapper;
- import testwebapp.com.wangzuojia.service.Human;
- import testwebapp.com.wangzuojia.service.SequenceService;
- @Service
- public class SequenceServiceImpl implements SequenceService {
- @Resource
- private SequenceMapper sequenceMapper;
- public void generateId(Map<String, String> map) {
- sequenceMapper.generateId(map);
- }
- //起服务此处会报错
- @Resource
- private Human human;
- }
这时候启动tomcat会包如下错误:
严重: Exception sendingcontext initialized event to listener instance of classorg.springframework.web.context.ContextLoaderListenerorg.springframework.beans.factory.BeanCreationException: Error creating beanwith name 'sequenceServiceImpl': Injection of resource dependencies failed;nested exception isorg.springframework.beans.factory.NoUniqueBeanDefinitionException: Noqualifying bean of type [testwebapp.com.wangzuojia.service.Human] is defined:expected single matching beanbut found 2: manImpl,womanImpl atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) atorg.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838) atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) atorg.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) atorg.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) atorg.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) atorg.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717) atorg.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)atorg.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) atorg.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404) atorg.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394) atjava.util.concurrent.FutureTask.run(FutureTask.java:266) atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) atjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)atjava.lang.Thread.run(Thread.java:745) Caused by:org.springframework.beans.factory.NoUniqueBeanDefinitionException: Noqualifying bean of type [testwebapp.com.wangzuojia.service.Human] is defined: expectedsingle matching bean but found 2: manImpl,womanImpl atorg.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1126) atorg.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:508) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:486) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615) atorg.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) atorg.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) atorg.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308) ...22 more
报错的地方给我们提示了:but found 2: manImpl,womanImpl 意思是Human有两个实现类。解决方案如下:
- package testwebapp.com.wangzuojia.service.impl;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- import testwebapp.com.wangzuojia.dao.SequenceMapper;
- import testwebapp.com.wangzuojia.service.Human;
- import testwebapp.com.wangzuojia.service.SequenceService;
- @Service
- public class SequenceServiceImpl implements SequenceService {
- @Resource
- private SequenceMapper sequenceMapper;
- public void generateId(Map<String, String> map) {
- sequenceMapper.generateId(map);
- }
- @Resource(name = "manImpl")//注意是manImpl不是ManImpl,因为使用@Service,容器为我们创建bean时默认类名首字母小写
- private Human human;
- }
这样启动服务就不会报错了。如果是使用的@Autowired注解,要配上@Qualifier("manImpl"),代码如下:
- package testwebapp.com.wangzuojia.service.impl;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Service;
- import testwebapp.com.wangzuojia.dao.SequenceMapper;
- import testwebapp.com.wangzuojia.service.Human;
- import testwebapp.com.wangzuojia.service.SequenceService;
- @Service
- public class SequenceServiceImpl implements SequenceService {
- @Resource
- private SequenceMapper sequenceMapper;
- public void generateId(Map<String, String> map) {
- sequenceMapper.generateId(map);
- }
- @Autowired
- @Qualifier("manImpl")
- private Human human;
- }
总结:
1、@Autowired是spring自带的,@Inject是JSR330规范实现的,@Resource是JSR250规范实现的,需要导入不同的包
2、@Autowired、@Inject用法基本一样,不同的是@Autowired有一个request属性
3、@Autowired、@Inject是默认按照类型匹配的,@Resource是按照名称匹配的
4、@Autowired如果需要按照名称匹配需要和@Qualifier一起使用,@Inject和@Name一起使用