Spring笔记 01:使用注解配置Bean

本文详细介绍了Spring中注解配置Bean的方法,包括配置扫描的条件,如@Component及其派生注解,扫描包及过滤规则。接着讲解了自动装配Bean的@Autowired和@Resource的用法,如何处理找不到Bean的异常,以及如何处理多个相同类型的Bean。最后,文章还提到了其他注解,如@Scope、@PostConstruct和@PreDestroy,涉及Bean的作用域和生命周期管理。
摘要由CSDN通过智能技术生成

1. 配置扫描的条件

使用注解标识一个类(@Component,@Controller,@Repository,@Service)

//value属性指定当前类的对象在容器中的id
@Component(value = "car")
public class Car {
   
}

在配置文件中配置要扫描的包,Spring会扫描该包及其子包下的所有类(context:component-scan标签)

<context:component-scan base-package="com.dudu.beans"/>

指定扫描的资源(resource-pattern属性)

<context:component-scan 
        base-package="com.dudu.beans"
        resource-pattern="dao/*.class"/>

指定排除哪些资源(context:exclude-filter子节点)

<context:component-scan base-package="com.dudu.beans">
    <!-- 指定排除有Controller注解的类 -->
    <context:exclude-filter type="annotation"
                            expression="org.springframework.stereotype.Controller"/>
    <!-- 指定排除UserDao接口及其所有的实现类 -->
    <context:exclude-filter type="assignable" expression="com.dudu.beans.dao.UserDao"/>
</context:component-scan>

指定包含哪些资源,此时要禁用默认的filter(context:include-filter子节点)

<context:component-scan base-package="com.dudu.beans"
                        use-default-filters="false">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值