<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>