文章参考来源:Spring Framework官方文档
1. @Component及进一步的构造型注解
无论是@Component,@Service,@Repository还是@Controller,都是Spring提供的进一步原型注解。@Component是任何spring托管组件的通用构造型。@Repository、@Service和@Controller是@Component用于更具体用例的专门化(分别用在持久性、服务层和表示层中)。因此,可以用@Component来标注组件类,但是,通过用@Repository、@Service或@Controller来标注更适合通过工具进行处理或与方面相关联的类。例如,这些构造型注释是切入点的理想目标。@Repository、@Service和@Controller也可以在Spring框架的未来版本中携带额外的语义。因此,如果要在服务层使用@Component还是@Service之间进行选择,@Service显然是更好的选择。类似地,如前所述,@Repository已经被支持作为持久性层中自动异常转换的标记。
2. 使用元注解组成新注解
比如@Service 注解的组成,就有@Component注解的参与。@RestController也是由@Controller 和@ResponseBody注解组成。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
// ...
}
此外,组合注解可以选择性地重新声明元注解的属性,以允许自定义。比如Spring的@SessionScope注解将作用域名称硬编码为会话,但仍然允许定制proxyMode。
3. 关于路径扫描
以下两种都可以起到相同的作用:使用XML或者纯注解配置的扫描
(1)注解开启扫描
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
// ...
}
以上表明:开启扫描,扫描路径为:org.example
此时像下面的@Repository注解的类(在org.example路径下),就会被扫描并纳入到容器管理中。
@Repository
public class JpaMovieFinder implements MovieFinder {
// implementation elided for clarity
}
(2)XML开启扫描
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
其中,<context:component-scan>的使用,隐式包含了<context:annotation-config>,所以不必再增加<context:annotation-config>。
且当开启组件扫描元素时(注解或者XML),AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor都是隐式包含的。这意味着这两个组件被自动检测并连接在一起—所有这些都不需要在XML中提供任何bean配置元数据。