可以用@Controller @Service @Commpont @Repository 这4个都能进行组件扫描
原文如下:
Spring提供了更多的构造型注解:@Component, @Service, 和@Controller. @Component 可用于管理任何Spring的组件。 @Repository, @Service, 或 @Controller是@Component的特殊化。用于更具体的用例(分别在持久性,服务和表示层中)。 因此,您可以使用@Component注解组件类,但是,通过使用@Repository, @Service, 和 @Controller注解它们,能够让你的类更易于被合适的工具处理或与相应的切面关联。 例如,这些注解可以使目标组件变成切入点。在Spring框架的未来版本中,@Repository, @Service, 和 @Controller也可能带有附加的语义。 因此,如果在使用@Component 或 @Service 来选择服务层时,@Service显然是更好的选择。同理,在持久化层要选择@Repository,它能自动转换异常。
使用方法很简单只要在类上面加上那四个注解就可以了
@Component
public class MyAnnotation {
public void add(){
System.out.println("add...");
}
}
使用xml进行扫描
<!--base-package 扫描的包路径-->
<context:component-scan base-package="com.gq.demo.annotation" ></context:component-scan>
<!--只扫描哪些内容 多个用逗号隔开-->
<context:component-scan base-package="com.gq.demo.annotation" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--哪些不用扫描-->
<context:component-scan base-package="com.gq.demo.annotation" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>