SpringBoot注解全解:35个核心注解开发手册

🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

SpringBoot注解全解:35个核心注解开发手册

一、Spring Boot启动注解

1.1 @SpringBootApplication

@SpringBootApplication 是一个组合注解,它包含了 @SpringBootConfiguration@EnableAutoConfiguration@ComponentScan 这三个重要的注解。它是Spring Boot应用的入口,通常用于主类上。

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

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

1.2 @EnableAutoConfiguration

@EnableAutoConfiguration 会根据类路径中的依赖自动配置Spring应用程序。例如,当类路径中存在Tomcat时,它会自动配置嵌入式Tomcat服务器。

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
public class MyAutoConfig {
    // 配置类代码
}

二、Spring Boot配置注解

2.1 @Configuration

@Configuration 用于定义配置类,相当于传统的XML配置文件。在配置类中可以使用 @Bean 注解来定义Bean。

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

@Configuration
public class MyConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

2.2 @PropertySource

@PropertySource 用于加载外部属性文件,例如 .properties.yml 文件。

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

@Configuration
@PropertySource("classpath:my.properties")
public class MyConfigWithProperties {
    // 配置类代码
}

2.3 @Value

@Value 用于注入属性值,可以从属性文件中读取值。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    @Value("${my.property}")
    private String myProperty;

    // getter 和 setter 方法
}

2.4 @ConfigurationProperties

@ConfigurationProperties 用于将配置文件中的属性绑定到Java类上。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "my.config")
public class MyConfigProperties {
    private String name;
    private int age;

    // getter 和 setter 方法
}

三、Spring Boot组件注解

3.1 @Component

@Component 是一个通用的组件注解,用于将类标记为Spring的组件,让Spring自动扫描并创建Bean。

import org.springframework.stereotype.Component;

@Component
public class MyComponentClass {
    // 组件类代码
}

3.2 @Service

@Service@Component 的一个特化注解,通常用于标记业务逻辑层的类。

import org.springframework.stereotype.Service;

@Service
public class MyServiceClass {
    public void doSomething() {
        // 业务逻辑代码
    }
}

3.3 @Repository

@Repository@Component 的一个特化注解,通常用于标记数据访问层的类,例如DAO类。

import org.springframework.stereotype.Repository;

@Repository
public class MyRepositoryClass {
    public void saveData() {
        // 数据访问代码
    }
}

3.4 @Controller

@Controller@Component 的一个特化注解,通常用于标记控制器层的类。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello, World!";
    }
}

四、Spring Boot Web注解

4.1 @RestController

@RestController@Controller@ResponseBody 的组合注解,用于创建RESTful风格的控制器。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {
    @GetMapping("/api/hello")
    public String helloApi() {
        return "Hello from API!";
    }
}

4.2 @RequestMapping

@RequestMapping 用于映射HTTP请求到控制器的处理方法。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/my")
public class MyRequestMappingController {
    @RequestMapping("/test")
    public String test() {
        return "Test mapping";
    }
}

4.3 @GetMapping、@PostMapping、@PutMapping、@DeleteMapping

这些注解是 @RequestMapping 的特定HTTP方法的快捷方式。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/http")
public class MyHttpMethodController {
    @GetMapping("/get")
    public String getMethod() {
        return "GET method";
    }

    @PostMapping("/post")
    public String postMethod() {
        return "POST method";
    }
}

4.4 @RequestBody

@RequestBody 用于将HTTP请求的主体绑定到方法的参数上。

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/body")
public class MyRequestBodyController {
    @PostMapping("/test")
    public String testRequestBody(@RequestBody String body) {
        return "Received: " + body;
    }
}

4.5 @PathVariable

@PathVariable 用于从URL路径中获取变量值。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/path")
public class MyPathVariableController {
    @GetMapping("/{id}")
    public String getById(@PathVariable int id) {
        return "ID: " + id;
    }
}

4.6 @RequestParam

@RequestParam 用于从HTTP请求的参数中获取值。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/param")
public class MyRequestParamController {
    @GetMapping("/test")
    public String testRequestParam(@RequestParam String name) {
        return "Name: " + name;
    }
}

五、Spring Boot AOP注解

5.1 @Aspect

@Aspect 用于定义切面类,切面类中可以包含切点和通知。

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceMethods() {}

    @Before("serviceMethods()")
    public void beforeServiceMethod() {
        System.out.println("Before service method");
    }
}

5.2 @Pointcut

@Pointcut 用于定义切点,切点表达式指定了哪些方法会被拦截。

5.3 @Before

@Before 是一个前置通知,在目标方法执行之前执行。

5.4 @After

@After 是一个后置通知,在目标方法执行之后执行,无论目标方法是否抛出异常。

5.5 @AfterReturning

@AfterReturning 是一个返回通知,在目标方法正常返回后执行。

5.6 @AfterThrowing

@AfterThrowing 是一个异常通知,在目标方法抛出异常时执行。

5.7 @Around

@Around 是一个环绕通知,可以在目标方法执行前后进行增强。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAroundAspect {
    @Around("execution(* com.example.service.*.*(..))")
    public Object aroundServiceMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Before around advice");
        Object result = joinPoint.proceed();
        System.out.println("After around advice");
        return result;
    }
}

六、Spring Boot事务注解

6.1 @Transactional

@Transactional 用于开启事务管理,可以在方法或类上使用。

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MyTransactionalService {
    @Transactional
    public void doTransactionalWork() {
        // 事务操作代码
    }
}

七、Spring Boot测试注解

7.1 @SpringBootTest

@SpringBootTest 用于启动完整的Spring Boot应用程序上下文进行集成测试。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MySpringBootTest {
    @Autowired
    private MyService myService;

    @Test
    public void testService() {
        myService.doSomething();
    }
}

7.2 @WebMvcTest

@WebMvcTest 用于测试Spring MVC控制器,只加载与控制器相关的组件。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(MyRestController.class)
public class MyWebMvcTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHelloApi() throws Exception {
        mockMvc.perform(get("/api/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello from API!"));
    }
}

八、其他Spring Boot注解

8.1 @ConditionalOnClass

@ConditionalOnClass 用于根据类路径中是否存在指定的类来决定是否加载配置。

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(name = "com.example.SomeClass")
public class MyConditionalConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

8.2 @ConditionalOnMissingBean

@ConditionalOnMissingBean 用于在容器中不存在指定类型的Bean时才创建Bean。

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyMissingBeanConfig {
    @Bean
    @ConditionalOnMissingBean
    public MyService myService() {
        return new MyService();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanxbl957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值