10个不可不知的Spring Boot注释方法

whdahanh 发布于 2023-08-30 336 次阅读


本文详细介绍10个pring Boot注释方法,并附有示例,帮助你更好理解。

长按关注《Java学研大本营》

本文介绍您需要了解的几个基本的Spring Boot应用程序注释,都附有详细的解释,希望能帮助您更好的理解。

1 @SpringBootApplication

我们在应用程序的主类中使用此注释用来启用Spring Boot的自动配置和组件扫描等功能。

SpringBootApplication注释的作用是与以下注释相结合:

  • @EnableAutoConfiguration - 启用Spring Boot的自动配置功能。
  • @ComponentScan - 启用组件扫描。
  • @Configuration - 启用基于Java的配置。

示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

 public static void main(String[] args) {
  SpringApplication.run(MyApplication.classargs);
 }

}

2 @Component

我们在类级别使用此注释,用@Component注释的类将被扫描为Spring管理的bean,我们不需要编写显式代码来扫描创建的自定义bean。

Spring还提供了3个特定的构造型注释,用于将类作为组件 - Service、Controller和Repository(在后面的部分中讨论)

示例:

import org.springframework.stereotype.Component;


@Component
public class HelloWorld {
    //逻辑

3 @Service

这是将类注释为服务层,这意味着该类将保存应用程序的业务逻辑,没有其他用途。

@Service
public class HelloWorld {
//业务逻辑
}

4 @Repository

它与处理应用程序的DAO(Data Access Object) 层的类一起使用,或者与处理数据库CRUD操作的repository类一起使用。

@Repository
public class HelloWorld {
//数据库CRUD操作
}

5 @Controller

使用@Controller注释的类将处理所有用户请求并返回适当的响应。此注释用于Restful Web服务以处理请求和响应。

6  @RequestMapping

此注释与@Controller注释一起使用,将HTTP请求映射到适当的处理程序方法。这可以在类级别或方法级别使用。

@Controller和@RequestMapping的示例:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/hello")
public class HelloWorld {
//HTTP 方法
}

7 @Autowired

Autowired自动注入Spring管理的组件依赖项,简单来说,它为您初始化对象。

@Controller
@RequestMapping("/hello")
public class HelloWorld {
    @Autowired 
    HelloService helloService;
//HTTP 方法
}

8 @Qualifier

当Spring找到具有相同类型的多个bean时,处理依赖项注入时可能存在歧义,使用@Qualifier注释,我们可以指定要注入的bean的名称。

@Controller
@RequestMapping("/hello")
public class HelloWorld {

    @Autowired 
    @Qualifier("helloServiceBean")
    HelloService helloService;
//HTTP 方法
}

9 @Bean

这是方法级别的注释,用于在Spring上下文中管理返回的bean。它通常在配置类中使用。

10 @Configuration

使用@Configuration注释的类表示该类将用于声明多个方法以返回Spring beans。

@Configuration和@Bean注解的示例:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 

@Configuration
public class HelloWorld {

    @Bean
    public HelloClass collegeBean()
    {
        return new HelloClass();
    }
}

这段是Spring框架中@Configuration和@Bean注解的示例。@Configuration注解用于将一个类标记为配置类,在应用程序中进行自动扫描和管理。@Bean注解用于将一个方法标记为生产bean的方法,这些 bean可以在应用程序中被自动扫描和管理。在此示例中,这两个注解被一起使用,将HelloWorld类标记为配置类,并将collegeBean()方法标记为生产bean的方法,以便在应用程序中进行自动扫描和管理。

本篇文章来源于微信公众号:作者:原创 学研妹 Java学研大本营 Java学研大本营 微信号 java_study_camp 功能介绍 Java编程、后端、大数据、架构师、Spring、Apache、Linux开发 发表于

转载地址:https://mp.weixin.qq.com/s/6C8MPtyXtsR9pk_uh8mlrA



微信扫描下方的二维码阅读本文

此作者没有提供个人介绍
最后更新于 2023-08-30