(笔记)Spring实战_最小化Spring XML配置(3)_自动检测Bean

<context:component-scan>元素除了完成与<context:annotation-config>一样的工作,还允许Spring自动检测Bean和定义Bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.springinaction.springimage" />

</beans>

<context:component-scan>元素会扫描指定的包及其所有子包,并查找出能够自动注册为Spring Bean的类。
1.为自动检测标注Bean
@Component——通用的构造型注解,标识该类为Spring组件。
@Controller——标识将该类定义为Spring MVC controller。
@Repository——标识将该类定义为数据仓库。
@Service——标识将该类定义为服务。
@使用@Component标注的任意自定义注解。

package com.springinaction.springimage;


import org.springframework.stereotype.Component;


@Component
public class Saxophone implements Instrument
{
    public Saxophone()
    {

    }

    public void play()
    {
        System.out.println("TOOT TOOT TOOT");
    }
}

Bean的ID默认为无限定类名。

package com.springinaction.springimage;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component("eddie")
public class Instrumentalist implements Performer
{

    public void perform()
    {
        System.out.print("Playing " + song + " : ");
        instrument.play();
    }

    private String song;

    @Value("Jingle Bells")
    public void setSong(String song)
    {
        this.song = song;
    }

    public String getSong()
    {
        return song;
    }

    private Instrument instrument;

    @Autowired
    @Qualifier("saxophone")
    public void setInstrument(Instrument instrument)
    {
        this.instrument = instrument;
    }

}

2.过滤组件扫描
默认是基于注解的组件扫描策略。

过滤器类型描述
annotation过滤器扫描使用指定注解所标注的那些类。通过expression属性指定要扫描的注解
assignable过滤器扫描派生于expression属性所指定类型的那些类
aspectj过滤器扫描与expression属性所指定的AspectJ表达式所匹配的那些类
custom使用自定义的org.springframework.core.type.TypeFilter实现类,该类由expression属性指定
aspectj过滤器扫描类的名称与expression属性所指定的正则表达式所匹配的那些类
    <context:component-scan base-package="com.springinaction.springimage">
        <context:include-filter type="assignable"
            expression="com.springinaction.springimage.Instrument" />
        <context:exclude-filter type="annotation"
            expression="com.springinaction.springimage.SkipIt" />
    </context:component-scan>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值