不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2021-02-24 15:30:29  修改时间:2024-03-29 19:11:26  分类:Java框架/系统  编辑

官方

Annotation Meaning
@Component generic stereotype for any Spring-managed component
@Repository stereotype for persistence layer  【DAO层】
@Service stereotype for service layer
@Controller stereotype for presentation layer (spring-mvc)

相似

上述官话,只说明了 Spring 中 该类注解用途,但没讲明,有些情况下它们为什么可以互用

  • 强调一点,对于 BeanDefinition 自动扫描检测和依赖注入,所有这些注解(即 @Component,@Service,@Repository,@Controller)都是相同的,它们彼此可以相互替换

差异

  • @Component 的特殊之处
    • 是一个通用的构造型注解,表明该类是一个 Spring 组件
    • <context:component-scan> 仅在于扫描 @Component 并且不会查找 @Controller,@Service,@Repository 一般而言。扫描它们是因为它们本身都带有注释 @Component, 看源码定义便知
@Component
public @interface Service {
    ….
}
@Component
public @interface Repository {
    ….
}
@Component
public @interface Controller {
    …
}

Spring 中存在一批注解的注解,类似组合设计,有些注解只是其他注解的组合(如 RestController = Response+Controller),有些注解则是配合主注解(如条件注解)

  • @Controller,@Service 并且 @Repository 是特殊类型的 @Component 注解。
  • <context:component-scan> 选择它们并将它们的后续类注册为 bean,就像它们被注解一样 @Component
  • 还会扫描特殊类型的注释,因为它们本身都带有 @Component 注解的注解

@Repository

  • 表明该类定义了一个数据存储库
  • 除了指出这是一个基于注解的配置之外,@Repository 会捕获平台特定的异常并将它们重新抛出作为 Spring 统一的未经检查的异常之一。通常需要在 Spring 的应用程序上下文中添加如下配置 PersistenceExceptionTranslationPostProcessor
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

@Controller

  • 该 @Controller 被注解的类扮演控制器的角色
  • 不同于 @Service,@Repository 注解,程序调度器扫描该注解的类,在内部会去检测其用 @RequestMapping 注解的方法

配置 xml 还是 注解?

注解在其声明中提供了大量上下文,从而导致更短更简洁的配置。XML 擅长在不触及源代码或重新编译它们的情况下连接组件。 Spring 中的注解和 xml 配置,以及所谓的 java 配置类,最终将被 Spring ioc 容器内,表示为 BeanDefinition 对象,环境对象,profile 等相关的其它对象实例

  • 注解:是一种分散式的元数据,与源代码紧绑定
  • xml:是一种集中式的元数据,与源代码无绑定
  • 让 xm 有用的是,使用 xml 的类。同样让注解有效的是注解处理器,否则注解和注释没什么区别。
  • 注解这种机制是一种与 Java 编程语言无关的独立存在,它会让 java 语言更好,但不是语言必须的部分

 

摘自:https://learnku.com/articles/32522

 


Spring中@component的使用

@component是Spring中的一个注解,它的作用就是实现bean的注入,开发中我们可以使用注解 取代xml配置文件。

在探究@component前,先了解一下注解,何为注解?注解本质上就是一个类。

Web开发,提供3个@Component注解的衍生注解(功能一样)取代 @component

@Repository("名称"):dao层
@Service("名称"):service层
@Controller("名称"):web层

@Autowired:自动根据类型注入
@Qualifier("名称"):指定自动注入的id名称

@Resource("名称")
@PostConstruct:自定义初始化
@PreDestroy:自定义销毁

下面直接看具体例子:

(2)案例二

 

摘自:https://blog.csdn.net/qq_37606901/article/details/91357882