spring注解杂想

版权声明:欢迎技术爱好者前来讨论,转载请标明出处.谢谢 https://blog.csdn.net/qq_42875051 https://blog.csdn.net/qq_42875051/article/details/87447961

spring中的注解可以理解为spring框架打入的一个个标签,用来区分不同结构的,也可以是用来区分不同类型的.

@autowired 注解

当在类文件中使用@service  @Controller   或者 其他同类型的注解时,spring通过扫描,建立一个键值对照表,将这个类放入到一个bean类型的关系表里面,而这个class下的属性/方法则会被放入一个列表中,这个列表是以classname为key,一个linkedlist为值的列表,文件中出现了@Autowired   这种注解的时候就会根据这个注解下的名称对照前面关系表进行索引.如果索引成功的话就会将目标进行注入,如果索引不存在的话就会报出异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.krams.tutorial.controller.TestController.ix(com.mysite.controller.IndexController,com.mysite.nospring.data.Article); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mysite.nospring.data.Article] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

这个异常就是告诉我们,你使用的这个索引名称不在我的关系列表中,需要重新检查这个名称是否正确.

但是如果存在一个问题,有一个类被spring通过配置文件创建了两个实现类bean,这个时候单纯的@Autowired  就无法区分到底是哪个了,因为@Autowired  默认的注入方法是byType ,这个时候就需要通过辅助注解进行区分了 @Qualifier(value =“beanName”)  ,通过这个注解就可以通过beanname进行区分了.

参考文章:http://www.iocoder.cn/Spring/@Autowired/

猜你喜欢

转载自blog.csdn.net/qq_42875051/article/details/87447961