注解注入Bean

【1】注解类别

@Component : 基本注解, 标识了一个受 Spring 管理的组件 
@Repository : 标识持久层组件 
@Service : 标识服务层(业务层)组件 

@Controller : 标识表现层组件

【2】context:component-scan标签

<context:component-scan base-package="com.web.annotation"

    resource-pattern="repository/*.class"use-default-filters="true">

<context:include-filter> 子节点表示要包含的目标类

<context:exclude-filter> 子节点表示要排除在外的目标类

<context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点


如下配置将只扫描repository下的包:resource-pattern="repository/*.class"

默认fileter(use-default-filters="true")将扫描所有注解组件,若想使用 include-filter等,则将其改为false.

<context:component-scan base-package="com.web.annotation" resource-pattern="repository/*.class"

use-default-filters="true">

    <!-- 只包含Repository注解 ,其他不行-->

    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>

    <!-- 不包含Repository注解 ,其他可以-->

    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>

    <!-- 只包含Repository接口及其实现类 ,其他不行-->

    <context:include-filter type="assignable" expression="com.web.annotation.repository.UserRepository"/>

    <!-- 不包含Repository接口及其实现类 ,其他可以-->

    <context:exclude-filter type="assignable" expression="com.web.annotation.repository.UserRepository"/>

</context:component-scan>


@Primary注解

当没有使用@Qualifier注解,而又找到了多个该类型的bean时,@Primary注解让Spring进行自动装配的时候,默认使用首选的bean。

@Bean

标注的方法创建对象的时候,方法参数的值从容器中获取;@Autowired注解常常省略。

@Resource默认按照组件名称(byName)进行装配。还可以提供一个 bean name,以该name为id在容器中进行查询并装配。

使用@Resource注解时,@Primary注解将失效。该注解亦无required=false的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值