@Component放到类上面标注,可以使POJO类(普通的java类)转换为容器管理的bean
Spring还提供了三个等效注解
@Controller:对Controller实现类进行注解。
@Service:用于对Service进行类注解
@Responsitory:用于对DAO进行类注解
扫描注解定义的bean
在实现类上添加注解之后,还需要在配置文件中设置扫描类包才能让Spring容器识别到
<?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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.smart.anno"/>
</beans>
base-package属性指定要扫描的基类包,这里将扫描com.smart.anno下的所有类。
扫描特定的类
通过resource-pattern属性设置。
<context:component-scan base-package="com.smart" resource-pattern="anno/*.class"/>
这里扫描anno包下的类,而不是smart包下的所有类。
过滤指定的类
通过<context:include-filter>和<context:exclude-filter>属性设置。其中,前者表示要包含的类,后者表示排除的类。
<context:component-scan base-package="com.smart">
<context:include-filter type="regex" expression="com\.smart\.anno.*Dao"/>
<context:include-filter type="regex" expression="com\.smart\.anno.*Service"/>
<context:exclude-filter type="aspectj" expression="com.smart..*Controller+"/>
</context:component-scan>
注意⚠️
<context:component-scan />有一个容易被忽视的use-default-filters属性,默认值为true,表示默认会对标注@Component,@Contorller,@Service,@Responsitory的注解进行扫描。