Spring注解注入

一.使用@Autowired注解来装配bean。

@Autowired使用byType方式来装配Bean。

@Autowired不仅可以标注属性,而且还可以标注需要自动装配Bean引用的任意方法。

(1)如果没有适合类型的Bean装配到属性或者方法中。

默认情况下,@Autowired具有强契约性,其标注的属性或参数必须是可装配的。如果没有Bean可以装配到@Autowired所标注的属性或参数中,自动装配就会失败(抛出NoSuchBeanDefinitionException)。也可以让@Autowired标注的属性或参数为空值,将required属性设置为false

@Autowired(required=false)
private MyBean myBean;

(2)有多个相同类型的Bean可以被装配时

当有多个可以被装配的Bean时,使用@Autowired方式也会抛出异常。可以使用@Qualifier指定需要装配的Bean的id

@Autowired
@Qualifier("myBeanId")
private MyBean myBean;

二.使用<context:component-scan>来自动扫描类包,将添加了注解的类自动定义为Bean。

<context:component-scan>元素会扫描指定的包及其所有子包,并查找出能够自动注册为Spring Bean的类。base-package属性标识了<context:component-scan>所扫描的包。比如我有一个包:com.me.bean里面有我定义的bean。

<context:componenet-scan base-package="com.me.bean"/>

默认情况下,<context:componenet-scan>查找使用构造型(stereotype)注解所标注的类,这些特殊的注解如下。

@Componenet--------通用的构造型注解,标识该类为Spring组件。

@Controller-----------标识将该类定义为Spring MVC controller。

@Repository----------标识将该类定义为数据仓库。

@Service--------------标识将该类定义为服务。

使用@Component标注任意自定义注解。

在如何扫描来获得候选Bean方面,<context:componenet-scan>非常灵活。通过为<context:component-scan>配置<context:include-filter>,<context:exclude-filter>子元素,我们可以随意调整扫描行为。比如:

<context:component-scan
    base-package="com.spring.bean">
    <context:include-filter type="assignable"
        expression=“com.spring.bean.Instrument"/>
    <context:exclude-filter type="annotation"
        expression="com.spring.bean.SkipIt"/>
</context:component-scan>

在这里是用来了include-filter来告知哪些类需要注册为Spring Bean,exclude-filter来告知哪些类不需要注册为Spring Bean。

其中的type="assignabel"和type="annotaion"是两种过滤器类型

assignable过滤器派生于expression属性所指定类型的那些类。

annotation过滤器扫描使用指定注解所标注的那些类。通过expression属性指定要扫描的注解。

regex过滤器扫描类扫描类的名称与expression属性所指定的这则表达式所匹配的那些类。

原文地址:https://www.cnblogs.com/ironmantony/p/3510303.html