@autowired注解 怎么生效
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@autowired注解 怎么生效相关的知识,希望对你有一定的参考价值。
参考技术A 使用Spring时,通过Spring注入的Bean一般都被定义成private,并且要有getter和setter方法,显得比较繁琐,增加了代码量,而且有时会搞忘造成错误。可以使用@Autowired注解来减少代码量。首先,在applicationContext中加入:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
Spring使用这个BeanPostProcessor解析@Autowired注解。
然后,在变量上添加@Autowired注解,并去掉相应的getter和setter方法:
复制代码
package com.school.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.school.dao.ClasDAO;
import com.school.entity.Clas;
public class ClasServiceImpl implements ClasService
@Autowired
private ClasDAO clasDAO;
...
复制代码
并且在applicationContext中将相应的<property></property>标签去掉:
<bean id="clasService" class="com.school.service.ClasServiceImpl">
</bean>
Spring启动时,AutowiredAnnotationBeanPostProcessor会扫描所有的Bean,当发现其中有@Autowired注解时,就会找相应类型的Bean,并且实现注入。本回答被提问者采纳
@Resource与@Autowired注解的区别
一、写本博文的原因
年初刚加入到现在的项目时,在使用注解时我用的@Resource。后来,同事:你怎么使用@Resource注解?我:使用它有错吗?同事:没错,但是现在都使用@Autowired。我:我研究一下。
在大学,学习J2EE实训时一直使用的是@Resource注解,后来我就养成习惯了。现在对这两个注解做一下解释:
- @Resource默认按照名称方式进行bean匹配,@Autowired默认按照类型方式进行bean匹配
- @Resource(import javax.annotation.Resource;)是J2EE的注解,@Autowired( import org.springframework.beans.factory.annotation.Autowired;)是Spring的注解
Spring属于第三方的,J2EE是Java自己的东西。使用@Resource可以减少代码和Spring之间的耦合。
二、@Resource注入
现在有一个接口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;
- }
以上是关于@autowired注解 怎么生效的主要内容,如果未能解决你的问题,请参考以下文章
Spring-----注解实现自动装配(自动匹配属性类型) @Autowired 和 autowire
详解Spring中@Autowire,@Value 注解实现原理