目录
@ToString(exclude = {"field1", "field2"})
@ToString(of = {"field1", "field2"})
@JsonAnyGetter 和 @JsonAnySetter
@JsonSerialize 和 @JsonDeserialize
@EnableConfigurationProperties
@EnableElasticsearchRepositories
Spring Boot 常用注解汇总
启动注解 @SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
@SpringBootApplication
是一个复合注解,包含了 @SpringBootConfiguration
、@EnableAutoConfiguration
和 @ComponentScan
这三个注解。它的作用是启动 Spring Boot 应用,并自动配置 Spring 应用程序上下文。
@SpringBootConfiguration
这个注解继承自 @Configuration
,表示当前类是一个配置类。它会把类中用 @Bean
注解标记的方法返回的对象注册到 Spring 容器中,实例名就是方法名。
@SpringBootConfiguration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@EnableAutoConfiguration
这个注解开启了 Spring Boot 的自动配置功能。它会根据项目的依赖自动配置 Spring 应用程序上下文。Spring Boot 通过 SpringFactoriesLoader
加载所有符合条件的配置类,并应用到当前应用中。
@EnableAutoConfiguration
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@ComponentScan
这个注解用于自动扫描并加载符合条件的组件或 Bean 定义。默认情况下,它会扫描当前包及其子包下的所有组件。你可以通过 basePackages 属性指定扫描的包路径。
@ComponentScan(basePackages = "com.example")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
二、Controller 相关注解
@Controller
用于标记一个类为 Spring MVC 的控制器,处理 HTTP 请求。
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
@RestController
这是一个复合注解,相当于 @Controller
+ @ResponseBody
。它通常用于 RESTful Web 服务,返回的数据会直接以 JSON 格式展示在浏览器中。
@RestController
public class MyRestController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
@RequestBody
用于将 HTTP 请求体中的 JSON 数据反序列化为 Java 对象。
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@RequestMapping
用于将 HTTP 请求映射到控制器的方法上。可以通过 method
属性指定请求方法(如 GET、POST 等)。
@RequestMapping(value = "/user", method = RequestMethod.GET)
public User getUser(@RequestParam("id") Long id) {
return userService.findById(id);
}
@GetMapping 和 @PostMapping
分别是 @RequestMapping
的简写形式,专门用于处理 GET 和 POST 请求。
@GetMapping("/user")
public User getUser(@RequestParam("id") Long id) {
return userService.findById(id);
}
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
三、取请求参数值
@PathVariable
用于从 URL 路径中获取参数值。
@Controller
@RequestMapping("/User")
public class HelloWorldController {
@RequestMapping("/getUser/{uid}")
public String getUser(@PathVariable("uid") Integer id, Model model) {
System.out.println("id:" + id);
return "user";
}
}
@RequestParam
用于从请求参数中获取值。
@Controller
@RequestMapping("/User")
public class HelloWorldController {
@RequestMapping("/getUser")
public String getUser(@RequestParam("uid") Integer id, Model model) {
System.out.println("id:" + id);
return "user";
}
}
@RequestHeader
用于从请求头中获取值。
@GetMapping("/header")
public String getHeader(@RequestHeader("User-Agent") String userAgent) {
return "User-Agent: " + userAgent;
}
@CookieValue
用于从请求的 Cookie 中获取值。
@GetMapping("/cookie")
public String getCookie(@CookieValue("JSESSIONID") String cookie) {
return "JSESSIONID: " + cookie;
}
四、注入 Bean 相关
@Repository
用于标记 DAO 层的类,通常与 JPA 一起使用。
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
@Service
用于标记服务层的类。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User save(User user) {
return userRepository.save(user);
}
}
@Scope
用于指定 Bean 的作用域,如 prototype、singleton 等。
@Service
@Scope("prototype")
public class UserService {
// ...
}
@Entity
用于标记实体类,通常与 JPA 一起使用。
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
}
@Bean
用于在配置类中定义一个 Bean。
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Autowired
用于自动注入依赖。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
@Component
用于标记一个类为 Spring 组件,Spring 会自动扫描并注册为 Bean。
@Component
public class MyComponent {
// ...
}
五、导入配置文件
@PropertySource
用于加载指定的配置文件。
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${app.name}")
private String appName;
}
@ImportResource
用于导入 XML 配置文件。
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
// ...
}
@Import
用于导入额外的配置类。
@SpringBootApplication
@Import({SmsConfig.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
六、事务注解
@Transactional
用于声明事务管理,通常用在服务层的方法上。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public User save(User user) {
return userRepository.save(user);
}
}
七、全局异常处理
@ControllerAdvice
用于全局异常处理,可以统一处理控制器抛出的异常。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
String handleException() {
return "Exception Deal!";
}
}
@ExceptionHandler
用于声明异常处理方法。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
String handleException() {
return "Exception Deal!";
}
}
八、@Conditional系列
@Conditional
系列注解用于根据特定条件来决定是否加载某个 Bean 或配置类。Spring Boot 提供了多个 @Conditional
的变体,用于不同的场景。
@ConditionalOnProperty
根据配置文件中的属性值来决定是否加载 Bean。
@Configuration
public class AppConfig {
@Bean
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
public MyFeature myFeature() {
return new MyFeature();
}
}
@ConditionalOnClass
当类路径中存在指定的类时,才加载 Bean。
@Configuration
@ConditionalOnClass(MyService.class)
public class MyServiceAutoConfiguration {
@Bean
public MyService myService() {
return new MyService();
}
}
@ConditionalOnMissingBean
当 Spring 容器中不存在指定类型的 Bean 时,才加载当前 Bean。
@Configuration
public class AppConfig {
@Bean
@ConditionalOnMissingBean
public MyService myService() {
return new MyService();
}
}
@ConditionalOnExpression
根据 SpEL 表达式的值来决定是否加载 Bean。
@Configuration
@ConditionalOnExpression("${app.feature.enabled:false} && ${app.feature.mode:test} == 'production'")
public class MyFeatureConfig {
@Bean
public MyFeature myFeature() {
return new MyFeature();
}
}
九、@ToString 系列注解
@ToString
是 Lombok 提供的注解,用于自动生成 toString()
方法。它可以减少样板代码,提高代码的可读性。
@ToString
自动生成 toString()
方法,包含所有字段。
@ToString
public class User {
private Long id;
private String name;
}
@ToString(exclude = {"field1", "field2"})
排除指定字段,不包含在 toString()
方法中。
@ToString(exclude = {"id"})
public class User {
private Long id;
private String name;
}
@ToString(of = {"field1", "field2"})
只包含指定字段在 toString()
方法中。
@ToString(of = {"name"})
public class User {
private Long id;
private String name;
}
十、@Validation 系列注解
@Validation
系列注解用于数据校验,通常与 @Valid
或 @Validated
一起使用。
@NotNull
校验字段不能为 null
。
public class User {
@NotNull
private String name;
}
@NotEmpty
校验字段不能为空(字符串不能为空,集合不能为空)。
public class User {
@NotEmpty
private String name;
}
@NotBlank
校验字符串不能为空且不能只包含空白字符。
public class User {
@NotBlank
private String name;
}
@Size
校验字段的长度或大小。
public class User {
@Size(min = 2, max = 30)
private String name;
}
@Min 和 @Max
校验数字的最小值和最大值。
public class User {
@Min(18)
@Max(100)
private int age;
}
校验字段是否为合法的电子邮件地址。
public class User {
@Email
private String email;
}
@Pattern
校验字段是否符合指定的正则表达式。
public class User {
@Pattern(regexp = "^[a-zA-Z0-9]{5,10}$")
private String username;
}
@Valid 和 @Validated
用于触发数据校验。
@RestController
public class UserController {
@PostMapping("/user")
public User createUser(@Valid @RequestBody User user) {
return userService.save(user);
}
}
十一、JSON 系列注解
JSON 系列注解主要用于控制 Java 对象与 JSON 数据之间的序列化和反序列化行为。
@JsonIgnore
忽略某个字段,不参与序列化和反序列化。
public class User {
@JsonIgnore
private String password;
}
@JsonFormat
指定日期或时间字段的格式。
public class User {
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthDate;
}
@JsonProperty
指定字段在 JSON 中的名称。
public class User {
@JsonProperty("user_name")
private String name;
}
@JsonInclude
控制序列化时是否包含某些字段。例如,只包含非空字段。
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private String name;
private Integer age;
}
@JsonCreator
用于指定反序列化时的构造函数或工厂方法。
public class User {
private String name;
private int age;
@JsonCreator
public User(@JsonProperty("name") String name, @JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
}
@JsonAnyGetter 和 @JsonAnySetter
用于处理动态属性。
public class User {
private Map<String, Object> properties = new HashMap<>();
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
}
@JsonAnySetter
public void setProperty(String key, Object value) {
properties.put(key, value);
}
}
@JsonSerialize 和 @JsonDeserialize
用于自定义序列化和反序列化逻辑。
public class User {
@JsonSerialize(using = CustomSerializer.class)
@JsonDeserialize(using = CustomDeserializer.class)
private String name;
}
十二、@Configuration 系列注解
@Configuration
系列注解用于定义配置类,通常与 @Bean
注解一起使用,用于将 Bean 注册到 Spring 容器中。
@Configuration
标记一个类为配置类,Spring 会将其中的 @Bean
方法注册为 Bean。
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Import
用于导入其他配置类。
@Configuration
@Import({DatabaseConfig.class, SecurityConfig.class})
public class AppConfig {
}
@ImportResource
用于导入 XML 配置文件。
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
}
@PropertySource
用于加载指定的配置文件。
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${app.name}")
private String appName;
}
@ConfigurationProperties
用于将配置文件中的属性绑定到 Java 对象上。
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String version;
// getters and setters
}
十三、@Slf4j 系列注解
@Slf4j
是 Lombok 提供的注解,用于自动生成日志对象,简化日志记录代码。
@Slf4j
自动生成 log
对象,用于记录日志。
@Slf4j
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
@CommonsLog
生成 Apache Commons Logging 的日志对象。
@CommonsLog
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
@Log4j
生成 Log4j 的日志对象。
@Log4j
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
@Log4j2
生成 Log4j2 的日志对象。
@Log4j2
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
@JBossLog
生成 JBoss Logging 的日志对象。
@JBossLog
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
十四、@Data 系列注解
@Data
是 Lombok 提供的注解,用于自动生成 getter
、setter
、toString
、equals
和 hashCode
方法,减少样板代码。
@Data
生成 getter
、setter
、toString
、equals
和 hashCode
方法。
@Data
public class User {
private Long id;
private String name;
}
@Getter 和 @Setter
分别生成 getter
和 setter
方法。
public class User {
@Getter @Setter
private Long id;
@Getter @Setter
private String name;
}
@ToString
生成 toString
方法。
@ToString
public class User {
private Long id;
private String name;
}
@EqualsAndHashCode
生成 equals
和 hashCode
方法。
@EqualsAndHashCode
public class User {
private Long id;
private String name;
}
@NoArgsConstructor
生成无参构造函数。
@NoArgsConstructor
public class User {
private Long id;
private String name;
}
@AllArgsConstructor
生成全参构造函数。
@AllArgsConstructor
public class User {
private Long id;
private String name;
}
@RequiredArgsConstructor
生成包含 final
字段和 @NonNull
字段的构造函数。
@RequiredArgsConstructor
public class User {
private final Long id;
@NonNull
private String name;
}
十五、@Builder 注解
@Builder
是 Lombok 提供的注解,用于生成 Builder 模式的代码,简化对象的创建。
@Builder
生成 Builder 模式的代码。
@Builder
public class User {
private Long id;
private String name;
}
// 使用 Builder 创建对象
User user = User.builder()
.id(1L)
.name("John")
.build();
@Singular
用于集合类型的字段,生成添加单个元素的方法。
@Builder
public class User {
private Long id;
private String name;
@Singular
private List<String> roles;
}
// 使用 Builder 创建对象
User user = User.builder()
.id(1L)
.name("John")
.role("ADMIN")
.role("USER")
.build();
十六、@Api 系列注解
@Api
系列注解是 Swagger 提供的注解,用于生成 API 文档。
@Api
用于标记一个类为 Swagger 资源。
@Api(value = "User Management", description = "Operations pertaining to user management")
@RestController
public class UserController {
// ...
}
@ApiOperation
用于描述一个 API 操作。
@ApiOperation(value = "Get a user by ID", response = User.class)
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@ApiParam
用于描述 API 操作的参数。
@ApiOperation(value = "Create a new user")
@PostMapping("/user")
public User createUser(@ApiParam(value = "User object to be created", required = true) @RequestBody User user) {
return userService.save(user);
}
@ApiModel
用于描述一个模型类。
@ApiModel(description = "User entity")
public class User {
@ApiModelProperty(value = "User ID", required = true)
private Long id;
@ApiModelProperty(value = "User name", required = true)
private String name;
}
@ApiModelProperty
用于描述模型类的属性。
@ApiModel(description = "User entity")
public class User {
@ApiModelProperty(value = "User ID", required = true)
private Long id;
@ApiModelProperty(value = "User name", required = true)
private String name;
}
@ApiResponse
用于描述 API 操作的响应。
@ApiOperation(value = "Get a user by ID", response = User.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved user"),
@ApiResponse(code = 404, message = "User not found")
})
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@ApiResponses
用于描述多个 API 操作的响应。
@ApiOperation(value = "Get a user by ID", response = User.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved user"),
@ApiResponse(code = 404, message = "User not found")
})
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
十七、其他常用注解
@ConfigurationProperties
用于将配置文件中的属性绑定到 Java 对象上。
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String version;
// getters and setters
}
@Conditional
用于条件化配置,根据条件决定是否加载某个 Bean。
@Configuration
public class AppConfig {
@Bean
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
public MyFeature myFeature() {
return new MyFeature();
}
}
@Async
用于声明异步执行的方法。
@Service
public class UserService {
@Async
public void asyncMethod() {
// 异步执行的代码
}
}
@Scheduled
用于声明定时任务。
@Service
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("Current time: " + new Date());
}
}
@Cacheable
用于缓存方法的结果。
@Service
public class UserService {
@Cacheable("users")
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
@Valid 和 @Validated
用于数据校验。
@RestController
public class UserController {
@PostMapping("/user")
public User createUser(@Valid @RequestBody User user) {
return userService.save(user);
}
}
@Profile
用于根据环境配置加载不同的 Bean。
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@CrossOrigin
用于支持跨域请求。
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
@EnableCaching
用于启用缓存。
@SpringBootApplication
@EnableCaching
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableAsync
用于启用异步执行。
@SpringBootApplication
@EnableAsync
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableScheduling
用于启用定时任务。
@SpringBootApplication
@EnableScheduling
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableAspectJAutoProxy
用于启用 AOP 代理。
@SpringBootApplication
@EnableAspectJAutoProxy
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableTransactionManagement
用于启用事务管理。
@SpringBootApplication
@EnableTransactionManagement
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableWebMvc
用于启用 Spring MVC 配置。
@SpringBootApplication
@EnableWebMvc
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableJpaRepositories
用于启用 JPA 仓库。
@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.repository")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableAutoConfiguration
用于启用自动配置。
@SpringBootApplication
@EnableAutoConfiguration
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableConfigurationProperties
用于启用配置属性绑定。
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableDiscoveryClient
用于启用服务发现。
@SpringBootApplication
@EnableDiscoveryClient
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableFeignClients
用于启用 Feign 客户端。
@SpringBootApplication
@EnableFeignClients
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableCircuitBreaker
用于启用断路器。
@SpringBootApplication
@EnableCircuitBreaker
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableHystrixDashboard
用于启用 Hystrix 仪表盘。
@SpringBootApplication
@EnableHystrixDashboard
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableZuulProxy
用于启用 Zuul 代理。
@SpringBootApplication
@EnableZuulProxy
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableSwagger2
用于启用 Swagger 文档。
@SpringBootApplication
@EnableSwagger2
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableMongoRepositories
用于启用 MongoDB 仓库。
@SpringBootApplication
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableRedisRepositories
用于启用 Redis 仓库。
@SpringBootApplication
@EnableRedisRepositories(basePackages = "com.example.repository")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableElasticsearchRepositories
用于启用 Elasticsearch 仓库。
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.example.repository")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableKafka
用于启用 Kafka 支持。
@SpringBootApplication
@EnableKafka
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableRabbit
用于启用 RabbitMQ 支持。
@SpringBootApplication
@EnableRabbit
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableBatchProcessing
用于启用批处理支持。
@SpringBootApplication
@EnableBatchProcessing
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableIntegration
用于启用 Spring Integration 支持。
@SpringBootApplication
@EnableIntegration
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableWebSecurity
用于启用 Spring Security 支持。
@SpringBootApplication
@EnableWebSecurity
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableOAuth2Sso
用于启用 OAuth2 单点登录支持。
@SpringBootApplication
@EnableOAuth2Sso
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@EnableResourceServer
用于启用资源服务器支持。
@SpringBootApplication
@EnableResourceServer
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
总结说明
以上是常见关于springboot的注解,大家熟练记忆,足以满足Java开发中springboot单体架构项目了,希望能够帮到大家,有帮助可以点赞收藏下来慢慢看。
本人码字不易,希望能够帮到大家!
平台声明:以上文章转载于《CSDN》,文章全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,仅作参考。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/lxx913318/article/details/146300734