常用注解有哪些?(@Configuration, @Bean, @Autowired, @Value等)

Spring Boot 常用注解详解

一、核心注解分类

1.配置类注解

@Configuration
  • 用途:声明一个类为配置类,相当于XML配置文件

  • 特点:会被CGLIB代理,确保@Bean方法返回单例

@Configuration public class AppConfig { // 内部可以定义@Bean方法 }
@Bean
  • 用途:在配置类中声明Bean,将方法返回值加入Spring容器

  • 属性

    • name/value:Bean名称(默认方法名)

    • initMethod/destroyMethod:初始化和销毁方法

@Configuration public class AppConfig { @Bean(name = "dataSource") public DataSource dataSource() { return new HikariDataSource(); } @Bean(initMethod = "init", destroyMethod = "cleanup") public MyService myService() { return new MyService(); } }

2.依赖注入注解

@Autowired
  • 用途:自动注入依赖,可省略setter方法

  • 注入方式

// 1. 字段注入(最常用) @Service public class UserService { @Autowired private UserRepository userRepository; } // 2. 构造器注入(Spring 4.3+可省略@Autowired) @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } } // 3. Setter方法注入 @Service public class UserService { private UserRepository userRepository; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } }
@Qualifier
  • 用途:配合@Autowired,指定注入的Bean名称

@Component @Qualifier("mysqlDataSource") public class MysqlDataSource implements DataSource { } @Component @Qualifier("oracleDataSource") public class OracleDataSource implements DataSource { } @Service public class ReportService { @Autowired @Qualifier("mysqlDataSource") private DataSource dataSource; }
@Resource
  • JSR-250标准:功能类似@Autowired,但默认按名称注入

@Component public class OrderService { @Resource(name = "userService") // 按名称注入 private UserService userService; }
@Inject
  • JSR-330标准:功能同@Autowired,需额外依赖

<dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>

3.属性配置注解

@Value
  • 用途:注入配置文件值、SpEL表达式

  • 使用方式

@Component public class AppConfig { // 1. 注入简单值 @Value("${app.name}") private String appName; // 2. 默认值 @Value("${app.version:1.0.0}") private String version; // 3. 数组/列表 @Value("${app.servers:localhost}") private String[] servers; // 4. SpEL表达式 @Value("#{systemProperties['java.home']}") private String javaHome; // 5. 系统环境变量 @Value("#{environment['JAVA_HOME']}") private String javaEnv; }
@ConfigurationProperties
  • 用途:批量绑定配置属性到对象

@Component @ConfigurationProperties(prefix = "app.datasource") public class DataSourceProperties { private String url; private String username; private String password; private int maxPoolSize = 10; // getters/setters } // application.yml app: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456 max-pool-size: 20

4.组件扫描注解

@ComponentScan
  • 用途:定义扫描的包路径

@SpringBootApplication @ComponentScan(basePackages = {"com.example.service", "com.example.dao"}) public class Application { }
组件类型注解

注解

层级

用途

@Component

通用

通用组件

@Service

服务层

业务逻辑组件

@Repository

持久层

数据访问组件

@Controller

控制层

MVC控制器

@RestController

控制层

REST API控制器

使用示例

@Repository public class UserRepository { } @Service public class UserService { @Autowired private UserRepository userRepository; } @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getUsers() { return userService.findAll(); } }

5.条件注解

注解

条件

@ConditionalOnBean

存在指定Bean时生效

@ConditionalOnMissingBean

不存在指定Bean时生效

@ConditionalOnClass

类路径存在指定类时生效

@ConditionalOnMissingClass

类路径不存在指定类时生效

@ConditionalOnProperty

配置属性匹配时生效

@ConditionalOnExpression

SpEL表达式为true时生效

@ConditionalOnJava

指定Java版本时生效

@ConditionalOnWebApplication

Web应用时生效

@ConditionalOnNotWebApplication

非Web应用时生效

@Configuration @ConditionalOnClass(DataSource.class) @ConditionalOnProperty(name = "spring.datasource.enable", havingValue = "true") public class DataSourceConfig { @Bean @ConditionalOnMissingBean public DataSource dataSource() { // 创建数据源 } }

6.事务注解

@Transactional
  • 用途:声明式事务管理

@Service public class OrderService { @Transactional( propagation = Propagation.REQUIRED, // 传播行为 isolation = Isolation.DEFAULT, // 隔离级别 timeout = 30, // 超时时间(秒) rollbackFor = Exception.class, // 回滚异常 noRollbackFor = RuntimeException.class // 不回滚异常 ) public void createOrder(Order order) { // 业务逻辑 } }

传播行为类型

public enum Propagation { REQUIRED, // 支持当前事务,不存在则新建 SUPPORTS, // 支持当前事务,不存在则以非事务执行 MANDATORY, // 必须存在事务 REQUIRES_NEW, // 新建事务,挂起当前事务 NOT_SUPPORTED, // 非事务执行,挂起当前事务 NEVER, // 必须非事务执行 NESTED // 嵌套事务 }

7.AOP相关注解

@Aspect
@Aspect @Component public class LogAspect { // 1. 前置通知 @Before("execution(* com.example.service.*.*(..))") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("方法执行前: " + joinPoint.getSignature().getName()); } // 2. 后置通知 @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void afterReturningAdvice(JoinPoint joinPoint, Object result) { System.out.println("方法返回: " + result); } // 3. 环绕通知 @Around("execution(* com.example.service.*.*(..))") public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { // 前置逻辑 Object result = joinPoint.proceed(); // 后置逻辑 return result; } }

8.测试相关注解

@SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") // 使用test配置文件 class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; // 模拟Bean @Test @DisplayName("测试用户查询") void testGetUser() throws Exception { Mockito.when(userService.findById(1L)) .thenReturn(new User(1L, "张三")); mockMvc.perform(get("/users/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("张三")); } }

9.Profile注解

@Profile
  • 用途:根据环境激活不同的配置

@Configuration public class DataSourceConfig { @Bean @Profile("dev") // 开发环境 public DataSource devDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } @Bean @Profile("prod") // 生产环境 public DataSource prodDataSource() { HikariDataSource ds = new HikariDataSource(); ds.setJdbcUrl("jdbc:mysql://prod-server:3306/db"); return ds; } }

10.定时任务注解

@Configuration @EnableScheduling public class ScheduleConfig { @Scheduled(fixedRate = 5000) // 每5秒执行 public void task1() { // 定时任务1 } @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行 public void task2() { // 定时任务2 } }

11.异步处理注解

@Configuration @EnableAsync public class AsyncConfig { @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); return executor; } } @Service public class AsyncService { @Async public CompletableFuture<String> asyncMethod() { // 异步执行 return CompletableFuture.completedFuture("结果"); } }

二、注解对比表格

注解类型

主要注解

作用域

常用属性

配置

@Configuration

-

@Bean

方法

name, initMethod, destroyMethod

注入

@Autowired

字段/方法/构造器

required

@Qualifier

字段/参数

value

@Resource

字段/方法

name, type

@Value

字段/参数

value

组件

@Component

value

@Service

value

@Repository

value

@Controller

value

@RestController

-

条件

@ConditionalOnXxx

类/方法

各种条件

事务

@Transactional

类/方法

propagation, isolation, rollbackFor

AOP

@Aspect

value

@Before/@After

方法

value

@Around

方法

value

Profile

@Profile

类/方法

value

定时

@EnableScheduling

-

@Scheduled

方法

cron, fixedRate, fixedDelay

异步

@EnableAsync

-

@Async

方法

value

三、最佳实践

1.依赖注入选择

// 推荐:构造器注入(不可变依赖) @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } } // 可选:@Autowired字段注入(简洁) @Service public class UserService { @Autowired private UserRepository userRepository; }

2.配置属性管理

// 推荐:使用@ConfigurationProperties替代多个@Value @ConfigurationProperties(prefix = "app") @Data // Lombok注解 public class AppProperties { private String name; private String version; private List<String> servers = new ArrayList<>(); } // 简单配置使用@Value @Component public class SimpleConfig { @Value("${app.name}") private String appName; }

3.条件化配置

@Configuration @ConditionalOnClass({DataSource.class, JdbcTemplate.class}) @ConditionalOnProperty(name = "spring.datasource.enable", havingValue = "true") @AutoConfigureAfter(DataSourceAutoConfiguration.class) public class JdbcConfig { // JDBC相关配置 }

四、常见问题

1.@Autowired与@Resource区别

特性

@Autowired

@Resource

来源

Spring框架

JSR-250标准

注入方式

默认按类型

默认按名称

必需性

required=true

必需

适用性

Spring项目

JavaEE/Spring项目

2.@Component vs @Bean

  • @Component:类级别注解,自动扫描注册

  • @Bean:方法级别注解,在配置类中显式声明

3.@Value注入失败处理

// 设置默认值 @Value("${app.port:8080}") private int port; // 使用Optional @Value("${app.port:#{null}}") private Optional<Integer> port;

总结

Spring Boot注解大大简化了配置工作,但需注意:

  1. 合理选择注入方式,优先使用构造器注入

  2. 理解注解的生命周期和作用范围

  3. 善用条件注解实现环境适配

  4. 遵循注解的默认约定,减少显式配置

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1156470.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

QSPI时序参数详解:超详细版调试指南

QSPI时序调优实战&#xff1a;从寄存器配置到信号完整性的深度拆解你有没有遇到过这样的场景&#xff1f;系统上电后偶尔卡死&#xff0c;JTAG一接上去却发现程序指针跑飞到了非法地址&#xff1b;或者在OTA升级时&#xff0c;固件读出来校验失败&#xff0c;但换块板子又正常—…

结合Proteus 8 Professional下载开展的电子竞赛培训实战案例

从仿真到实战&#xff1a;用Proteus打造电子竞赛的“预演战场” 一次“没焊电路板”的完整项目开发 去年带学生备战全国大学生电子设计竞赛时&#xff0c;有个小组遇到了典型难题&#xff1a;他们要做一个基于单片机的温控系统&#xff0c;但手头没有DS18B20温度传感器模块&…

Keil安装与ST-Link驱动兼容性问题全面讲解

Keil与ST-Link调试环境搭建&#xff1a;从驱动冲突到稳定连接的实战指南 你有没有遇到过这样的场景&#xff1f;刚装好Keil&#xff0c;满怀期待地打开uVision准备烧录程序&#xff0c;结果点击“Download”却弹出一串红字&#xff1a;“No ST-Link Detected”、“Cortex-M Acc…

高速时钟稳定性设计:STM32CubeMX核心要点

高速时钟稳定性设计&#xff1a;STM32CubeMX实战精要你有没有遇到过这样的问题&#xff1f;系统冷启动偶尔“卡死”&#xff0c;ADC采样值莫名漂移&#xff0c;USB通信频繁断开……排查半天软硬件&#xff0c;最后发现——根源竟是时钟配置不当。在嵌入式开发中&#xff0c;CPU…

手把手教程:如何高效克隆一个Demo代码仓库!

克隆Demo代码仓库是参与开源项目或学习开发实践的关键起点。借助Git命令行或图形化工具&#xff0c;用户可以将远程仓库完整复制到本地。本文将以清晰的步骤引导你完成整个克隆流程&#xff0c;确保新手也能快速上手。 一、下载模组的示例代码 下载示例代码到一个合适的项目目录…

嵌入式C语言在Keil uVision5中的编译优化策略

如何在 Keil uVision5 中用好编译优化&#xff1f;别让“快”毁了你的代码&#xff01; 你有没有遇到过这样的情况&#xff1a; 代码明明进了中断&#xff0c;标志也置位了&#xff0c;主循环却像没看见一样卡在 while(flag 0) &#xff1f; 切到 -O2 编译后&#xff0c…

STM32 Keil5破解详细步骤:超详细版安装说明

STM32开发环境搭建&#xff1a;Keil MDK-ARM 5配置与授权管理实战指南 在嵌入式系统的世界里&#xff0c;如果你正在使用STM32系列MCU&#xff0c;那么几乎绕不开一个名字—— Keil MDK 。作为ARM生态中历史最悠久、稳定性最强的集成开发环境之一&#xff0c;Keil Vision ID…

hh的蓝桥杯每日一题(交换瓶子)

15.交换瓶子 - 蓝桥云课 方法一&#xff1a;贪心做法 对于位置 i&#xff0c;如果 a[i] ≠ i 就把 a[i] 和 a[a[i]] 交换&#xff08;把当前数字放到它应该去的位置&#xff09; 这样每次交换都能让至少一个数字归位 重复直到 a[i] i #include<iostream> using na…

实验一 Python开发环境语法基础

实验一 Python开发环境&语法基础一、实验基本原理运用Anaconda搭建的Jupyter notebook平台编写实例Python程序。二、实验目的1、熟悉Python集成开发系统背景。2、熟悉Jupyter Notebook开发环境。3、熟悉编写程序的基本过程。三、具体要求1、熟悉Python的基本语法&#xff0…

LuatOS系统消息处理机制深度解析!

在LuatOS嵌入式运行环境中&#xff0c;系统消息是实现模块间通信与事件响应的核心机制。其消息处理机制采用轻量级事件驱动模型&#xff0c;有效降低CPU占用并提升系统实时性。此处列举了LuatOS框架中自带的系统消息列表。一、sys文档链接&#xff1a;https://docs.openluat.co…

避坑指南:LuatOS-Air脚本移植至LuatOS常见问题!

在实际开发中&#xff0c;许多开发者在尝试将LuatOS-Air脚本运行于标准LuatOS环境时遭遇报错或功能异常。这些问题多源于对底层驱动抽象层理解不足以及对系统任务模型的误用。本文将梳理典型错误场景&#xff0c;并提供可落地的修复方案&#xff0c;助力实现平滑迁移。 一、lua…

eide环境下GD32固件下载失败问题全面讲解

eIDE烧录GD32失败&#xff1f;从底层机制到实战排错的全链路技术拆解你有没有遇到过这样的场景&#xff1a;代码编译通过&#xff0c;接线看似没问题&#xff0c;点击“Download”按钮后却弹出一串红字——“Target Not Responding”、“Connection Failed”或干脆卡在“Connec…

实验二 Python 控制结构与文件操作

实验二 Python 控制结构与文件操作一、实验基本原理运用 Anaconda 搭建的 Jupyter notebook 平台编写 Python 实例程序。二、实验目的1、理解 Python 的流程控制、文件操作的基本原理。2、通过实际案例编程&#xff0c;掌握 Python 的流程控制、文件的基本操作。三、具体要求1、…

核心要点:避免USB Serial驱动下载后被系统禁用

一次连接&#xff0c;永久可用&#xff1a;破解USB Serial驱动被系统禁用的底层真相 你有没有遇到过这样的场景&#xff1f; 刚插上开发板&#xff0c;驱动安装成功&#xff0c;PuTTY连上了&#xff0c;日志哗哗地刷出来——一切看起来都那么完美。可第二天重启电脑&#xff…

Opensearch数据迁移:CCR功能数据迁移完整操作指南(上)

#作者&#xff1a;stackofumbrella 文章目录使用CCR功能迁移数据功能概述约束限制在主集群中创建索引从集群中执行启用CCR复制功能在主集群中写入测试数据在从集群中查看同步状态查看从集群中的同步数据关闭CCR功能查看远程集群信息删除远程集群配置信息使用CCR功能迁移数据 功…

计算机毕业设计-课程设计-校园失物招领系统设计与实现-程序-文档-全套资料

摘要学校作为一个人流量非常大的场所&#xff0c;当我们的物品不小心遗失后&#xff0c;之后的找寻过程一定是非常困难的。而为了可以解决这中问题&#xff0c;就出现了校园失物招领网站&#xff0c;通过校园失物招领网站&#xff0c;可以减少我们因为失物而带来的不便和困扰。…

Modbus RTU数据读取异常?ModbusPoll下载抓包辅助诊断

Modbus RTU通信总出问题&#xff1f;别急&#xff0c;用ModbusPoll抓包一招定位你有没有遇到过这样的场景&#xff1a;某台电表明明通着电、接线也没松动&#xff0c;但PLC就是读不到数据&#xff1b;或者HMI上某个温度值频繁跳变、甚至直接报超时&#xff1f;如果这个系统走的…

基于STM32的QSPI通信实战案例详解

STM32上的QSPI实战&#xff1a;从零搭建高速外部存储系统你有没有遇到过这样的困境&#xff1f;项目做到一半&#xff0c;内部Flash快爆了&#xff0c;GUI资源、音频文件、新功能代码全挤在一起&#xff0c;改一行代码都得精打细算&#xff1b;OTA升级时看着进度条一动不动&…

Keil项目迁移时中文注释乱码的预防与处理策略

如何彻底解决 Keil 中文注释乱码问题&#xff1f;一个嵌入式老手的实战经验最近接手了一个遗留项目&#xff0c;从同事手里接过压缩包解压后打开 Keil 工程&#xff0c;第一眼就傻了——满屏“ž„‹Œ–£”、“???”……原本清晰的中文注释全变成了天书。这哪是代码…

深入 Yak 语言高级编程:异步并发与延迟执行实践

深入Yak语言高级编程&#xff1a;异步并发与延迟执行实践 前言 Yak语言作为一款面向网络安全领域的动态编程语言&#xff0c;凭借其轻量、高效的特性&#xff0c;在渗透测试、漏洞挖掘等场景中得到了广泛应用。对于安全从业者而言&#xff0c;编写高性能的自动化脚本往往需要依…