ToB企服应用市场:ToB评测及商务社交产业平台

标题: SpringBoot注解大全(详细) [打印本页]

作者: 张国伟    时间: 2024-9-25 12:29
标题: SpringBoot注解大全(详细)




1. @ActiveProfiles

用来声明活动的profile–@ActiveProfiles(“prod”(这个prod定义在配置类中))
  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. @ActiveProfiles("test")  
  4. public class MyApplicationTests {  
  5.   
  6.     @Test  
  7.     public void contextLoads() {  
  8.         // 你的测试代码  
  9.     }  
  10. }
复制代码
@ActiveProfiles("test") 注解告诉 Spring框架激活名为 test 的配置文件。这意味着 Spring 将会加载与 test 配置文件相关的全部 bean 和配置。假如你有多个配置文件需要激活,可以使用逗号分隔它们,如 @ActiveProfiles("test,test1")。
2. @After

后置建言(advice),标志那些在每个测试方法执行之后都会运行的代码,和@Before相反
  1. import org.junit.After;  
  2. import org.junit.Before;  
  3. import org.junit.Test;  
  4.   
  5. public class MyTest {  
  6.   
  7.     @Before  
  8.     public void setUp() {  
  9.         // 在每个测试方法执行之前运行  
  10.     }  
  11.   
  12.     @Test  
  13.     public void testMethod1() {  
  14.         // 测试方法1  
  15.     }  
  16.   
  17.     @Test  
  18.     public void testMethod2() {  
  19.         // 测试方法2  
  20.     }  
  21.   
  22.     @After  
  23.     public void tearDown() {  
  24.         // 在每个测试方法执行之后运行  
  25.     }  
  26. }
复制代码
这个注解重要用于执行清算工作,比如释放资源、规复测试前的状态等,以确保测试的独立性和可重复性。
3. @Before

前置建言(advice),在原方法前执行。
4. @Around

环绕建言(advice),Spring AOP(面向切面编程)中的一个重要注解,环绕通知是一种在目的方法执行前后插入额外逻辑的增强处理,它可以在方法执行前进行操作,并在方法执行后进行操作,以致可以或许控制目的方法的执行与否、修改返回值或抛出非常。
  1. @Aspect  
  2. public class LoggingAspect {  
  3.   
  4.     @Around("execution(* com.example.service.*.*(..))")  
  5.     public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {  
  6.         long startTime = System.currentTimeMillis();  
  7.   
  8.         // 在目标方法执行之前执行的逻辑  
  9.         System.out.println("Method " + joinPoint.getSignature().getName() + " starts");  
  10.   
  11.         // 执行目标方法  
  12.         Object proceed = joinPoint.proceed();  
  13.   
  14.         // 在目标方法执行之后执行的逻辑  
  15.         long endTime = System.currentTimeMillis();  
  16.         System.out.println("Method " + joinPoint.getSignature().getName() + " ends. Execution time: " + (endTime - startTime) + " ms");  
  17.   
  18.         return proceed;  
  19.     }  
  20. }
复制代码
注意事项

5. @Aspect

Spring AOP(面向切面编程)中的一个核心注解,用于声明一个类为切面(Aspect)
@Aspect 的重要作用:

使用 @Aspect 的基本步骤:

  1.     @Aspect
  2.     @Component // 或者使用 @Configuration 和 @EnableAspectJAutoProxy  
  3.     public class LoggingAspect {
  4.         // 定义一个切入点表达式  
  5.         @Pointcut("execution(* com.example.service.*.*(..))")
  6.         public void serviceLayerExecution() {}
  7.         // 使用切入点表达式和 @Before 注解定义前置通知  
  8.         @Before("serviceLayerExecution()")
  9.         public void logBeforeServiceMethod(JoinPoint joinPoint) {
  10.             System.out.println("Before executing " + joinPoint.getSignature().getName());
  11.         }
  12. //         使用切入点表达式和 @Around 注解定义前置通知
  13. //        @Around("serviceLayerExecution()")
  14. //        public void logBeforeServiceMethod(JoinPoint joinPoint) {
  15. //            System.out.println("Around executing " + joinPoint.getSignature().getName());
  16. //        }
  17.         // 类似地,你可以定义其他类型的通知,如 @After、@AfterReturning、@AfterThrowing
复制代码
注意事项

6. @Autowired

Spring 框架中用于实现依赖注入的一个核心注解。它使得 Spring 容器可以或许主动地识别和注入标注了 @Autowired 的字段、构造器参数或方法参数所需的 bean。这极大地简化了依赖管理,使得开发者可以更加专注于业务逻辑的实现,而不是怎样配置和注入依赖
工作原理

当 Spring 容器启动时,它会扫描被 @Component、@Service、@Repository 或 @Controller 等注解标志的类,并将这些类的实例作为 bean 注册到 Spring 容器中。然后,对于每一个标注了 @Autowired 的字段、构造器或方法,Spring 容器会尝试在容器中查找一个类型匹配的 bean,并将其注入到被注解的位置。
使用场景

  1. @Autowired  
  2. private UserRepository userRepository;
复制代码
  1. @Autowired  
  2. public UserService(UserRepository userRepository) {  
  3.     this.userRepository = userRepository;  
  4. }
复制代码
  1. @Autowired  
  2. public void setUserRepository(UserRepository userRepository) {  
  3.     this.userRepository = userRepository;  
  4. }
复制代码
Demo

<img alt="image-20240923112722794" loading="lazy">

长处

注意事项

7. @Bean

Spring 框架中的一个核心注解,它重要用于在配置类中声明方法,并将这些方法的返回值注册为 Spring 容器中的 Bean
作用

使用

  1. @Configuration  
  2. public class AppConfig {  
  3.   
  4.     @Bean  
  5.     public UserService userService() {  
  6.         return new UserService();  
  7.     }  
  8. }
复制代码
特性

注意事项

8. @Component

Spring 框架中的一个核心注解,它重要用于标识一个类作为 Spring 容器中的组件,成为Spring管理的Bean。当使用基于注解的配置和类路径扫描时,这些类被视为主动检测的候选对象。同时@Component照旧一个元注解。
作用

使用

衍生注解

依赖注入

注意事项

9. @ComponentScan

用于指定 Spring 容器应该扫描哪些包来查找并注册带有特定注解的类(如 @Component、@Service、@Repository、@Controller 等)作为 Spring Bean
作用

根据定义的扫描路径,把符合扫描规则的类装配到 Spring 容器中。如许,Spring 容器就可以或许管理这些类的生命周期,并提供依赖注入等功能。
基本属性

@ComponentScan 注解包罗多个属性,用于自定义组件扫描的举动:
Demo

例如包布局如下:
  1. com  
  2. └── example  
  3.     └── myapp  
  4.         ├── AppConfig.java  
  5.         └── service  
  6.             ├── UserService.java  
  7.             └── ProductService.java
复制代码
在 UserService.java 和 ProductService.java 中,我们分别使用 @Service 注解标注了这两个类。然后,在 AppConfig.java 配置类中,我们可以使用 @ComponentScan 注解来指定 Spring 应该扫描的包:
  1. @Configuration  
  2. @ComponentScan(basePackages = "com.example.myapp")  
  3. public class AppConfig {  
  4.     // 这里可以定义其他配置 Bean 和设置  
  5. }
复制代码
在这个例子中,@ComponentScan 注解被用于 AppConfig 类上,指定 Spring 应该扫描 com.example.myapp 包及其子包,以将组件注册为 Spring Bean。
自定义过滤器

假如需要更细粒度的控制,可以通过 includeFilters 和 excludeFilters 属性来自定义过滤规则。例如,只扫描带有特定注解的类等
  1. @ComponentScan(  
  2.     basePackages = "com.example.myapp",  
  3.     useDefaultFilters = false,  
  4.     includeFilters = {  
  5.         @Filter(type = FilterType.ANNOTATION, classes = {MyCustomAnnotation.class})  
  6.     }  
  7. )
复制代码
10. @Configuration

它用于指示一个类声明了一个或多个 @Bean 方法,并且这些 @Bean 方法将被 Spring 容器管理,用于生成和管理 Spring 应用上下文中的对象(即 beans)。当你使用 @Configuration 注解一个类时,该类就变成了一个配置类(configuration class),Spring 容器会在启动时处理这个类,并识别出其中的 @Bean 方法。
重要特点

Demo
  1. import org.springframework.context.annotation.Bean;  
  2. import org.springframework.context.annotation.Configuration;  
  3.   
  4. @Configuration  
  5. public class AppConfig {  
  6.   
  7.     @Bean  
  8.     public MyService myService() {  
  9.         return new MyServiceImpl();  
  10.     }  
  11. }
复制代码
AppConfig 是一个配置类,它定义了一个名为 myService 的 @Bean 方法。当 Spring 容器启动时,它会调用 myService 方法来创建 MyService 接口的一个实现(MyServiceImpl),并将其注册为 Spring 应用上下文中的一个 bean。如许,你就可以在其他 Spring 管理的组件中通过主动装配(如 @Autowired)来注入这个 MyService bean 了。
注意事项

11. @ConfigurationProperties

它重要用于将配置文件(如 application.properties 或 application.yml)中的属性绑定到 Java 对象上。这个注解极大地简化了配置属性的读取和管理,使得开发者可以或许将外部配置与应用步伐代码解耦,提高代码的可维护性和可扩展性。
重要特点

Demo

  1. @Component
  2. @ConfigurationProperties(prefix = "myapp")
  3. public class MyAppProperties {
  4.     private String name;
  5.     private int version;
  6.     // getter 和 setter 方法
  7. }
复制代码
application.properties
  1. myapp.name=My App Name
  2. myapp.version=1.0.0
复制代码
application.yml
  1. myapp:
  2.   name: My App Name
  3.   version: 1.0.0
复制代码
  1. @Autowired  
  2. private MyAppProperties myAppProperties;  
  3. public void doSomething() {  
  4.     String name = myAppProperties.getName();  
  5.     int version = myAppProperties.getVersion();  
  6.     // 使用属性值进行其他操作  
  7. }
复制代码
注意事项

12. @ContextConfiguration

Spring 测试场景中经常使用,它重要用于加载和配置 Spring 上下文(ApplicationContext)。这个注解允许开发者指定要加载的配置文件或配置类的位置,以便在运行时或测试时可以或许精确地构建和初始化 Spring 上下文。
作用

使用

@ContextConfiguration 注解可以通过两种重要方式使用:
原理

13. @Controller

用于声明一个类作为 Spring MVC 控制器(Controller)。当一个类被 @Controller 注解标志时,Spring 容器会检测到这个类,并将其注册为一个 Spring MVC 控制器,从而可以或许处理通过 HTTP 请求映射的方法。
作用

Demo

  1. @Controller  
  2. public class MyController {  
  3. }
复制代码
  1. @Controller  
  2. public class MyController {  
  3.     @GetMapping("/hello")  
  4.     public String hello(Model model) {  
  5.         model.addAttribute("message", "Hello, Spring MVC!");  
  6.         return "hello"; // 返回视图名称,Spring MVC 会找到相应的视图模板进行渲染  
  7.     }  
  8. }
复制代码
  1. @Bean  
  2. public InternalResourceViewResolver viewResolver() {  
  3.     InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
  4.     resolver.setPrefix("/WEB-INF/views/");  
  5.     resolver.setSuffix(".jsp");  
  6.     return resolver;  
  7. }
复制代码
注意事项

14. @ExceptionHandler

Spring MVC 中的一个注解,用于处理控制器中抛出的非常。当你在控制器中处理请求时,可能会碰到各种非常情况,比如数据验证失败、资源找不到、权限不足等。使用 @ExceptionHandler 注解,你可以定义一个或多个方法来专门处理这些非常,从而避免在控制器方法中直接处理非常逻辑,使代码更加清晰和易于维护。
使用

Demo
  1. @Controller  
  2. public class MyController {  
  3.   
  4.     // 处理特定类型的异常  
  5.     @ExceptionHandler(value = MyCustomException.class)  
  6.     public ResponseEntity<String> handleMyCustomException(MyCustomException ex) {  
  7.         // 处理异常逻辑  
  8.         return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("自定义异常处理");  
  9.     }  
  10.   
  11.     // 处理所有未捕获的异常(可选)  
  12.     @ExceptionHandler(Exception.class)  
  13.     public String handleAllExceptions(Exception ex) {  
  14.         // 记录日志等操作  
  15.         return "error"; // 返回错误页面的视图名称  
  16.     }  
  17.   
  18.     // 控制器方法  
  19.     @GetMapping("/somePath")  
  20.     public String someMethod() {  
  21.         // 假设这里抛出了 MyCustomException 异常  
  22.         throw new MyCustomException("这是一个自定义异常");  
  23.     }  
  24.   
  25.     // 自定义异常类  
  26.     public static class MyCustomException extends RuntimeException {  
  27.         public MyCustomException(String message) {  
  28.             super(message);  
  29.         }  
  30.     }  
  31. }
复制代码
注意事项

15. @ModelAttribute

Spring框架中的一个注解,重要用于将HTTP请求中的数据绑定到模型对象,并在视图中进行渲染。它可以应用于方法参数或方法自己,具有灵活的数据处理本领。
使用

  1. @GetMapping("/users/{id}")  
  2. public String getUser(@PathVariable("id") int userId, @ModelAttribute("user") User user) {  
  3.     // 假设这里根据userId从数据库中获取User对象  
  4.     user = userService.getUserById(userId);  
  5.     // 方法执行时,user参数已经包含了从数据库获取的User对象  
  6.     // ...  
  7.     return "userPage";  
  8. }
复制代码
@ModelAttribute("user")注解将请求中或模型中名为"user"的属性绑定到User类型的参数user上。但请注意,这里的实际使用场景可能有所不同,因为通常我们不会将@ModelAttribute用于已经通过@PathVariable等注解获取了数据的参数上。这里的示例重要是为了阐明@ModelAttribute在方法参数上的用法。
  1. @ModelAttribute  
  2. public void addAttributes(Model model) {  
  3.     model.addAttribute("msg", "Hello, Spring MVC!");  
  4. }  
  5.   
  6. @GetMapping("/")  
  7. public String home() {  
  8.     // 这里可以直接使用模型中的"msg"属性  
  9.     // ...  
  10.     return "homePage";  
  11. }
复制代码
addAttributes方法使用了@ModelAttribute注解,其返回值(实际上是void,但通过model.addAttribute方法向模型中添加数据)会在每个请求处理方法之前执行,向模型中添加了一个名为"msg"的属性。如许,在后续的请求处理方法(如home方法)中就可以直接使用这个属性了。
特点

注意事项

16. @Transactional

Spring 框架中用于声明式事务管理的一个注解。它允许开发者通过简朴的注解来声明某个方法或类需要事务支持,而无需编写复杂的事务管理代码。Spring 会在运行时主动为这些方法或类创建署理对象,并在这些对象的方法执行时应用事务管理。
使用

使用

@Transactional 可以应用于接口定义、接口中的方法、类定义或类中的方法上。但是,请注意,由于 Spring 署理机制的限制,该注解在接口定义或接口方法上的效果可能不如预期,因此通常建议将其应用于具体的类方法上。
  1. @Service  
  2. public class MyService {  
  3.   
  4.     @Transactional  
  5.     public void myMethod() {  
  6.         // 执行数据库操作  
  7.     }  
  8. }
复制代码
myMethod 方法被标志为事务性的。当这个方法被调用时,Spring 会主动为这个方法的执行创建一个事务上下文,并在方法执行结束时根据是否出现非常来决定是提交事务照旧回滚事务。
属性

@Transactional 注解还提供了多个属性,允许开发者对事务的举动进行更细致的控制,例如:
注意事项

17. @Value

Spring 框架中的一个注解,它用于注入配置文件(如 properties 或 YAML 文件)中的值到 Spring 管理的 bean 的字段中。这个注解通常与 @ConfigurationProperties 或直接在 Spring 的组件(如 @Component、@Service、@Controller 等)中使用,以便从外部配置源(如 application.properties 或 application.yml 文件)中读取值。
使用

Demo
  1. app.name=MyApp  
  2. app.description=This is my application  
  3. app.enabled=true  
  4. app.number=123
复制代码
  1. import org.springframework.beans.factory.annotation.Value;  
  2. import org.springframework.stereotype.Component;  
  3.   
  4. @Component  
  5. public class MyAppProperties {  
  6.   
  7.     @Value("${app.name}")  
  8.     private String name;  
  9.   
  10.     @Value("${app.description}")  
  11.     private String description;  
  12.   
  13.     @Value("${app.enabled}")  
  14.     private boolean enabled;  
  15.   
  16.     @Value("${app.number}")  
  17.     private int number;  
  18.   
  19.     // getters and setters  
  20. }
复制代码
注意事项

18. @WebAppConfiguration

Spring框架中的一个类级别的注解,重要用于Spring MVC的集成测试中,以指定测试类所加载的ApplicationContext应该是一个WebApplicationContext。这个注解在测试过程中模仿了ServletContext,并构建了一个WebApplicationContext,从而为测试环境提供了Web应用步伐的环境。
作用

特性

Demo
  1. import org.springframework.test.context.ContextConfiguration;  
  2. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  3. import org.springframework.test.context.web.WebAppConfiguration;  
  4. import org.springframework.test.web.servlet.MockMvc;  
  5. import org.springframework.test.web.servlet.setup.MockMvcBuilders;  
  6. import org.springframework.web.context.WebApplicationContext;  
  7. import org.junit.Before;  
  8. import org.junit.Test;  
  9. import org.junit.runner.RunWith;  
  10.   
  11. @RunWith(SpringJUnit4ClassRunner.class)  
  12. @WebAppConfiguration  
  13. @ContextConfiguration("classpath:spring/applicationContext.xml")  
  14. public class MyWebControllerTests {  
  15.   
  16.     private MockMvc mockMvc;  
  17.   
  18.     @Autowired  
  19.     private WebApplicationContext webApplicationContext;  
  20.   
  21.     @Before  
  22.     public void setup() {  
  23.         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();  
  24.     }  
  25.   
  26.     @Test  
  27.     public void testMyController() throws Exception {  
  28.         // 使用mockMvc来模拟HTTP请求并验证响应  
  29.     }  
  30. }
复制代码
注意事项

19. @Order

用于定义Spring IOC容器中Bean的执行次序的优先级(这里的次序也可以明白为存放到容器中的先后次序)。它并不直接控制Bean的加载次序,而是影响Bean在特定场景下的执行次序,如依赖注入、事件监听、拦截器/过滤器执行等。
使用

Demo
  1. @Component  
  2. @Order(1)  
  3. public class FirstBean {  
  4.     // ...  
  5. }  
复制代码
  1. @Component  
  2. @Order(2)  
  3. public class SecondBean {  
  4.     // ...  
  5. }
复制代码
FirstBean将在SecondBean之前被创建(或按优先级执行,具体取决于上下文)。
注意事项

20. @SpringBootTest

是Spring Boot中一个非常重要的测试注解,它简化了集成测试的配置和执行过程,使得开发者可以或许更轻易地创建接近生产环境的测试环境。
作用

使用





Demo
  1. import org.junit.jupiter.api.Test;  
  2. import org.springframework.beans.factory.annotation.Autowired;  
  3. import org.springframework.boot.test.context.SpringBootTest;  
  4. import static org.junit.jupiter.api.Assertions.assertNotNull;  
  5.   
  6. @SpringBootTest  
  7. public class MyApplicationTests {  
  8.   
  9.     @Autowired  
  10.     private MyService myService;  
  11.   
  12.     @Test  
  13.     public void testService() {  
  14.         // 使用myService进行一些测试操作...  
  15.         assertNotNull(myService, "myService should not be null");  
  16.         // 其他测试逻辑...  
  17.     }  
  18. }
复制代码
@SpringBootTest注解确保了MyApplication的应用上下文被加载,从而使得MyService可以或许被主动注入到测试类中。如许我们就可以在测试中使用MyService,就像它被Spring管理一样,进行集成测试。
21. @PointCut

AspectJ框架(一个面向切面编程的框架)中的一个核心注解,在Spring AOP(面向切面编程)中也被广泛使用。它用于定义一个切入点(Pointcut),即指定在哪些连接点(Join Point)上应用某个切面(Aspect)的增强逻辑。
定义

组成

用法

Demo
  1. @Aspect
  2. @Component
  3. @Slf4j
  4. @Order(1)
  5. public class SqlLoggingAspect {
  6.     //定义切点
  7.     @Pointcut("execution(* org.example.mapper..*(..))")
  8.     public void repositoryExecution() {}
  9.     // 在切入点之前执行  
  10.     @Before("repositoryExecution()")
  11.     public void logBefore(JoinPoint joinPoint) {
  12.         log.debug("Executing method: " + joinPoint.getSignature().getName());
  13.         Object[] args = joinPoint.getArgs();
  14.     }
  15. }
复制代码
注意事项

22. @Service

Spring 框架中的一个注解,它用于标注在服务层(Service Layer)的组件上。Spring 框架的核心思想之一是依赖注入(Dependency Injection, DI),而 @Service 注解正是 Spring 依赖注入功能的一部分。通过使用 @Service 注解,Spring 可以或许主动地检测到被标注的类,并将着实例化、配置并管理起来,同时将这些实例注入到需要它们的类中(比如控制器层(Controller Layer)的类)。
作用

Demo
  1. import org.springframework.stereotype.Service;  
  2.   
  3. @Service  
  4. public class UserService {  
  5.   
  6.     // 这里可以注入其他依赖,比如数据访问层的组件  
  7.   
  8.     public User getUserById(Long id) {  
  9.         // 实现根据用户ID获取用户的业务逻辑  
  10.         // ...  
  11.         return new User();
  12.     }  
  13.   
  14.     // 其他业务方法...  
  15. }
复制代码
UserService 类被 @Service 注解标注,表示它是一个服务层组件。Spring 容器会主动检测到这个类,并将其注册为一个 Bean,然后就可以在需要的地方通过依赖注入的方式使用这个服务了。
注意事项

23. @SpingBootApplication

Spring Boot 中的一个核心注解,它重要用于标志 Spring Boot 应用的主配置类。这个注解是一个复合注解,它结合了多个其他 Spring 框架中的注解,以简化 Spring Boot 应用的配置和启动过程。
组成

@SpringBootApplication 注解实际上是以下三个注解的集合:
作用

Demo

@SpringBootApplication 注解会被添加到主类上
  1. import org.springframework.boot.SpringApplication;  
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  3.   
  4. @SpringBootApplication  
  5. public class MySpringBootApplication {  
  6.   
  7.     public static void main(String[] args) {  
  8.         SpringApplication.run(MySpringBootApplication.class, args);  
  9.     }  
  10.   
  11.     // 这里可以定义其他的方法或组件  
  12. }
复制代码
@SpringBootApplication 注解简化了启动 Spring Boot 应用的过程。当运行 main 方法时,Spring Boot 会主动进行配置并启动应用。
自定义配置

@SpringBootApplication 注解还允许开发者通过其属性进行自定义配置。例如,使用 exclude 属性可以排除特定的主动配置类,以避免不需要的主动配置。
24. @Profile

重要用于定义特定的配置环境(profile),以便在不同的环境中加载不同的配置或Bean
作用

使用

  1. @Configuration  
  2. @Profile("dev")  
  3. public class DevConfig {  
  4.     // 定义开发环境特有的Bean  
  5. }
复制代码
  1. @Configuration  
  2. public class DataSourceConfig {  
  3.       
  4.     @Bean  
  5.     @Profile("dev")  
  6.     public DataSource devDataSource() {  
  7.         // 返回开发环境的数据源  
  8.     }  
  9.     @Bean  
  10.     @Profile("prod")  
  11.     public DataSource prodDataSource() {  
  12.         // 返回生产环境的数据源  
  13.     }  
  14. }
复制代码
  1. @Bean  
  2. @Profile("dev,test")  
  3. public DataSource devTestDataSource() {  
  4.     // 返回开发和测试环境共有的数据源  
  5. }
复制代码
注意:使用的时候要激活Profile
在 application.properties 或 application.yml 文件中,通过设置 spring.profiles.active 属性来指定当前激活的Profile。
  1. # application.properties  
  2. spring.profiles.active=dev
复制代码
  1. # application.yml  
  2. spring:  
  3.   profiles:  
  4.     active: dev
复制代码
25. @Reponsitory

专门用于数据访问层(DAO层)的组件
作用

与其他注解关系

使用

Demo
  1. @Repository
  2. @Mapper
  3. public interface UserMapper {
  4.     List<UserModel> findAll();
  5.     UserModel findByName(String username);
  6.     String findPswByName(String userName);
  7.     void save(UserModel user);
  8. }
复制代码
  1. @Service
  2. public class UserserviceImpl implements UserService {
  3.     @Autowired
  4.     UserMapper userMapper;
  5.     // 登录操作
  6.     public String login(UserModel user) {
  7.         try {
  8.             UserModel userExistN = userMapper.findByName(user.getUsername());
  9.             if (userExistN != null) {
  10.                 String userExistP = userMapper.findPswByName(user.getUsername());
  11.                 if (userExistP.equals(user.getPassword())) {
  12.                     return user.getUsername()+"登录成功,欢迎您!";
  13.                 }else{
  14.                     return "登录失败,密码错误!";
  15.                 }
  16.             }else {
  17.                 return "登录失败,用户不存在!";
  18.             }
  19.         }catch (Exception e) {
  20.             e.printStackTrace();
  21.             return e.getMessage();
  22.         }
  23.     }
  24. }
复制代码
注意事项

26. @RequestBody

Spring MVC 和 Spring Boot 中常用的一个注解,它用于处理 HTTP 请求的 body 部分。当客户端发送一个请求到服务器时,请求体(body)通常包罗了要发送到服务器的数据。@RequestBody 注解告诉 Spring 的 DispatcherServlet,应该将请求体中的 JSON 或 XML 数据绑定到控制器(Controller)方法的参数上。
使用

原理

当控制器方法使用 @RequestBody 注解时,Spring 会使用 HttpMessageConverters 将请求体中的数据转换为 Java 对象。HttpMessageConverters 是一组用于转换 HTTP 请求和响应的类,它们负责将请求体中的数据转换为 Java 对象,以及将 Java 对象转换回响应体数据。
默认情况下,Spring Boot 提供了对 JSON 和 XML 的支持,因此你可以直接接收和发送 JSON 或 XML 数据。但是,你也可以通过添加其他库来支持其他格式的数据。
Demo
  1. // User.java  
  2. public class User {  
  3.     private Long id;  
  4.     private String name;  
  5.     // 省略getter和setter方法  
  6. }  
  7.   
  8. // UserController.java  
  9. @RestController  
  10. @RequestMapping("/users")  
  11. public class UserController {  
  12.   
  13.     @PostMapping("/add")  
  14.     public ResponseEntity<String> addUser(@RequestBody User user) {  
  15.         // 这里可以处理user对象,例如保存到数据库  
  16.         return ResponseEntity.ok("User added successfully!");  
  17.     }  
  18. }
复制代码
当客户端发送一个 POST 请求到 /users/add,并且请求体中包罗了一个 JSON 格式的 User 对象时,Spring 会主动将这个 JSON 数据转换成 User 类的实例,并将其作为 addUser 方法的参数传入。
注意事项

27. @RequestMapping

Spring MVC 中一个非常核心的注解,它用于将 HTTP 请求映射到特定的处理器(比如控制器中的一个方法)上。这个注解可以声明在类或方法上,用于定义请求的 URL、HTTP 方法(如 GET、POST)、请求参数、请求头等信息,以及它们怎样被映射到特定的处理函数上。
重要属性

使用

  1. @Controller  
  2. @RequestMapping("/users")  
  3. public class UserController {  
  4.   
  5.     @GetMapping("/{id}")  
  6.     public String getUserById(@PathVariable("id") Long id, Model model) {  
  7.         // 根据 id 获取用户信息,并填充到 model 中  
  8.         return "userDetail"; // 返回视图名  
  9.     }  
  10.   
  11.     @PostMapping  
  12.     public String createUser(@RequestParam String name, Model model) {  
  13.         // 创建用户  
  14.         return "userCreated";  
  15.     }  
  16. }
复制代码
@RequestMapping("/users") 应用于 UserController 类上,这意味着这个类中的全部请求 URL 都会以 /users 开头。然后,@GetMapping("/{id}") 和 @PostMapping 分别用于映射具体的 HTTP GET 和 POST 请求到不同的处理方法上。
2. 方法级别上的 @RequestMapping
  1. @Controller  
  2. public class MyController {  
  3.   
  4.     @RequestMapping(value = "/hello", method = RequestMethod.GET)  
  5.     public String sayHello() {  
  6.         return "hello"; // 返回视图名  
  7.     }  
  8.   
  9.     @RequestMapping(value = "/goodbye", method = RequestMethod.GET, params = "name")  
  10.     public String sayGoodbye(@RequestParam String name) {  
  11.         // 仅在请求中包含 'name' 参数时调用  
  12.         return "goodbye";  
  13.     }  
  14. }
复制代码
@RequestMapping 直接用于方法上,指定了请求的 URL 路径、HTTP 方法以及请求参数。params = "name" 表示这个请求必须包罗名为 name 的参数。
28. @ResponseBody

它用于将控制器的返回值绑定到 web 响应体(Response Body)上。当处理器方法被 @ResponseBody 注解时,Spring 会主动将方法的返回值写入到 HTTP 响应(HttpServletResponse)中。这个过程通常涉及到使用消息转换器(Message Converters)将返回值转换为适当的格式(如 JSON、XML 等),然后写入到响应体中。
作用

Demo

有一个用户对象 User 和一个控制器方法,你想要将 User 对象以 JSON 格式返回给客户端。
  1. @RestController // 这是一个方便的注解,相当于在每个方法上都加了 @Controller 和 @ResponseBody  
  2. public class UserController {  
  3.   
  4.     @GetMapping("/user/{id}")  
  5.     public User getUserById(@PathVariable Long id) {  
  6.         // 假设这里有一个服务或DAO层调用,根据id返回User对象  
  7.         User user = new User();  
  8.         user.setId(id);  
  9.         user.setName("John Doe");  
  10.         // 由于这里使用了 @RestController,或者如果只有这个方法使用了 @ResponseBody,  
  11.         // Spring 将自动将 User 对象序列化为 JSON 并写入响应体  
  12.         return user;  
  13.     }  
  14. }  
  15.   
  16. // 如果你没有使用 @RestController,但想要对单个方法应用 @ResponseBody,可以这样做:  
  17.   
  18. @Controller  
  19. public class UserController {  
  20.   
  21.     @GetMapping("/user/{id}")  
  22.     @ResponseBody // 告诉 Spring MVC 返回的内容应该绑定到响应体上  
  23.     public User getUserById(@PathVariable Long id) {  
  24.         // ... 与上面的示例相同  
  25.     }  
  26. }
复制代码
注意事项

29. @RestController

Spring 4.0 引入的一个注解,它是 @Controller 和 @ResponseBody 的组合注解。当你在一个类上使用 @RestController 注解时,意味着这个类中的全部方法都会默认应用 @ResponseBody 注解的效果,即方法的返回值会主动地绑定到 Web 响应体(Response Body)上,并且通常会被转换为 JSON 或 XML 等格式(这取决于配置的消息转换器)。
作用

Demo
  1. @RestController  
  2. public class UserController {  
  3.   
  4.     @GetMapping("/user/{id}")  
  5.     public User getUserById(@PathVariable Long id) {  
  6.         // 假设这里有一个服务或DAO层调用,根据id返回User对象  
  7.         User user = new User();  
  8.         user.setId(id);  
  9.         user.setName("John Doe");  
  10.         // 由于使用了 @RestController,Spring 会自动将 User 对象序列化为 JSON 并写入响应体  
  11.         return user;  
  12.     }  
  13.   
  14.     @PostMapping("/user")  
  15.     public ResponseEntity<String> createUser(@RequestBody User user) {  
  16.         // 假设这里有一个服务层调用,用于创建用户  
  17.         // 尽管这里返回的是 ResponseEntity,但 @RestController 仍然适用,因为它只关心返回值是否应该被写入响应体  
  18.         return ResponseEntity.ok("User created successfully");  
  19.     }  
  20. }
复制代码
getUserById 方法返回一个 User 对象,而 createUser 方法返回一个 ResponseEntity 对象。由于 UserController 类被 @RestController 注解,Spring 会主动处理这两个方法的返回值,将它们转换为 JSON(或其他配置的格式)并写入 HTTP 响应体中。
注意事项

30. @Async

用于声明一个异步方法。当你在方法上使用 @Async 注解时,Spring 会在调用该方法时,在一个单独的线程中异步地执行它。这意味着调用者线程不需要等待被 @Async 注解的方法执行完成,而是可以继续执行其他任务。
作用

使用

为了使用 @Async 注解,你需要满足以下条件:
Demo
  1. @Configuration  
  2. @EnableAsync  
  3. public class AsyncConfig {  
  4.     // 这里通常不需要实现任何bean,只需要@EnableAsync注解来启用异步支持  
  5. }
复制代码
  1. @Service  
  2. public class AsyncService {  
  3.   
  4.     @Async  
  5.     public Future<String> executeAsyncTask(int number) throws InterruptedException {  
  6.         // 模拟长时间运行的任务  
  7.         Thread.sleep(1000);  
  8.         return new AsyncResult<>("AsyncTask completed with value " + number);  
  9.     }  
  10.   
  11.     // 也可以返回void,但这样调用者就无法获取到执行结果  
  12.     @Async  
  13.     public void executeVoidAsyncTask(int number) {  
  14.         // 同样的长时间运行任务  
  15.         System.out.println("Executing void async task with number " + number);  
  16.     }  
  17. }  
复制代码
  1. @RestController  
  2. public class AsyncController {  
  3.   
  4.     @Autowired  
  5.     private AsyncService asyncService;  
  6.   
  7.     @GetMapping("/async/{number}")  
  8.     public ResponseEntity<String> asyncEndpoint(@PathVariable int number) throws ExecutionException, InterruptedException {  
  9.         Future<String> future = asyncService.executeAsyncTask(number);  
  10.         // 这里可以执行其他任务,而不需要等待异步方法完成  
  11.         String result = future.get(); // 获取异步方法的执行结果,这将阻塞直到异步方法完成  
  12.         return ResponseEntity.ok(result);  
  13.     }  
  14. }
复制代码
虽然 Future.get() 方法可以用来获取异步方法的执行效果,但它会阻塞调用线程直到异步方法完成。假如你想要避免阻塞,可以使用 CompletableFuture 并利用它的非阻塞API来处理异步效果。
注意事项

31. @AutoConfigureAfter

它重要用于指示某个主动配置类(Configuration Class)应该在指定的其他主动配置类之后进行主动配置。这个注解提供了一种机制来控制 Spring Boot 主动配置的次序,确保依赖关系的精确性,从而保证应用的精确性和可维护性。
作用

使用

Demo
  1. @Configuration  
  2. @AutoConfigureAfter(DataSourceAutoConfiguration.class)  
  3. public class MyAutoConfiguration {  
  4.     // ... 配置类的实现 ...  
  5. }
复制代码
MyAutoConfiguration 类将在 DataSourceAutoConfiguration 类之后进行主动配置。
注意事项

32. @Cacheable

重要用于声明性缓存,即将方法的返回值缓存起来,以便在后续雷同方法的调用中可以直接从缓存中获取效果,而无需再次执行方法的实际逻辑。如许做可以明显提高系统的性能和响应速度,特别是在处理读取操作频繁但数据更新不频繁的场景时。
作用

使用

在 Spring Boot 项目中,使用 @Cacheable 注解通常需要以下几个步骤:
参数

Demo
  1. @Service  
  2. public class MyService {  
  3.   
  4.     @Cacheable(value = "myCache", key = "#id")  
  5.     public String getData(int id) {  
  6.         // 模拟耗时操作  
  7.         try {  
  8.             Thread.sleep(2000);  
  9.         } catch (InterruptedException e) {  
  10.             e.printStackTrace();  
  11.         }  
  12.         // 实际的数据获取逻辑  
  13.         return "Data for id: " + id;  
  14.     }  
  15. }
复制代码
getData 方法的效果会被缓存到名为 myCache 的缓存中,缓存的键是方法的参数 id。当再次调用 getData 方法并传入雷同的 id 时,假如缓存中存在对应的效果,则直接返回缓存中的值,而不会执行方法的实际逻辑。
注意事项

33. @Conditional

用于在基于条件的情况下控制配置类的注册或Bean的创建。这个注解是 Spring 4.0 引入的,作为 Spring 的条件化配置的一部分,它提供了一种灵活的方式来控制哪些配置或Bean应该被包罗在Spring应用上下文中。
使用

@Conditional 注解通常与自定义条件类一起使用,这些条件类实现了 Condition 接口。通过实现 matches(ConditionContext, AnnotatedTypeMetadata) 方法,你可以定义何时应该包罗特定的配置类或Bean。这种方法非常适合于根据运行时环境(如操作系统类型、JVM版本、特定的库是否可用等)来条件化地包罗配置。
工作原理

Demo
  1. // 自定义条件类  
  2. public class OnWindowsCondition implements Condition {  
  3.     @Override  
  4.     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {  
  5.         // 检查操作系统是否为Windows  
  6.         return System.getProperty("os.name").toLowerCase().contains("win");  
  7.     }  
  8. }  
  9.   
  10. // 使用@Conditional注解  
  11. @Configuration  
  12. public class AppConfig {  
  13.   
  14.     @Bean  
  15.     @Conditional(OnWindowsCondition.class)  
  16.     public MyWindowsSpecificBean myWindowsSpecificBean() {  
  17.         return new MyWindowsSpecificBean();  
  18.     }  
  19. }
  20.    MyWindowsSpecificBean 只有在操作系统为Windows时才会被创建并注册到Spring应用上下文中。
复制代码
注意事项

34. @ConditionalOnBean

条件注解,用于在容器中存在特定 Bean 的情况下才创建当前 Bean。这个注解通常用在基于 Spring Boot 的应用中,与主动配置(Auto-configuration)功能结合使用,以根据应用的配置和已存在的 Bean 来条件化地注册新的 Bean。
使用

@ConditionalOnBean 注解可以应用于配置类中的 @Bean 方法上。当 Spring 容器中存在指定的 Bean 时,才会执行该方法并创建相应的 Bean。假如不存在指定的 Bean,则该方法会被忽略,不会创建任何 Bean。
属性

有一个 RedisTemplate 的 Bean,并且你只想在 RedisTemplate 存在时才创建 RedisOperBean
@ConditionalOnBean 注解包罗几个属性,用于指定条件细节:
<ul>value:Class[] 类型,指定需要存在的 Bean 的类型。
type:String[] 类型,与 value 属性类似,但允许使用 Bean 的名称(而不是类型)。
annotation:Class




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4