SpringBoot注解合集

目录

1 @SpringBootApplication

2 @ImportResource

3.@Autowired

4 Controller 相关

5.Bean相关


1 @SpringBootApplication

用在 Spring Boot 的主类上,标识着这个应用是一个 Spring Boot 应用, @SpringBootApplication 又是三个注解的组合,包含了:

  • @SpringBootConfiguration:源于 @Configuration,作用就是将当前类标注为配置类;

  • @EnableAutoConfiguration:自动配置,让 Spring Boot 应用将所有 @Configuration 配置都加载到 IoC 容器中;

  • @ComponentScan:将一些标注了特定注解的 bean 注册到 IoC 容器中,比如: @Controller、 @Component、 @Entity 等等。

2 @ImportResource

用于将加载 xxxx.xml 文件中的配置;比如老的 Spring 项目迁移到 Spring Boot 上,可以使用这个标签加载制定的配置文件

@SpringBootApplication

@ImportResource("classpath:beans.xml")

public class Chapter1Application { 

  public static void main(String[] args) {         
    SpringApplication.run(Chapter1Application.class, args); }
}

3.@Autowired

自动装配,会在 IoC 容器中查询对应类型的 Bean,如果查询到了,就装配上,如果查询不到,那么会抛出异常; @Autowired 可以消除 set、get 方法

4 Controller 相关

  • @Controller:标记在一个类上,表示这是一个 Controller 对象,是一个控制器类;

  • @RestController:等于 @Controller 和 @ResponseBody 的组合,方法返回的对象可以直接转化成 JSON 格式;

  • @RequestParam:接收请求头 Request Head 中的内容,比如 Content-Type 标识了具体请求中的资源类型,常用的 application/xml、 application/json 等等。

  • @PathVariable:获取 url 中的参数;

  • @RequestBody:读取请求体 Request Body ,并将其反序列化成 Java 对象;

  • @RequestMapping:将 http 请求映射到控制器上,也就是将请求路径和其处理类和方法进行绑定。

5.Bean相关

  • @Service:用于标注服务层组件,表示这是一个 Bean,Bean 的名称默认为当前类的名字,也可以传递参数,指定 Bean 的名称;

  • @Repository:数据库访问组件,也就是 DAO 层;

  • @Scope:用于配置作用域,比如设置 singleton 表示单例,prototype 每次都会创建一个新的对象等等;

  • @Entity:实体类,可以使用 @Table 注解和数据库中的表绑定,主键使用 @Id 标注,其余字段使用 @Column 进行标注(如果保持属性名和字段名一致,可以省略 @Column);

  • @Component:当组件不好归类的时候,可以使用 @Component 进行标注;

  • @Autowired:当我们需要使用组件的时候,可以使用 @Autowired 实现的 Bean 的自动注入。

猜你喜欢

转载自blog.csdn.net/weixin_40791454/article/details/107040192