文章目录

    • 前言
    • 1. 核心启动注解
      • @SpringBootApplication
      • @EnableAutoConfiguration
      • @SpringBootConfiguration
    • 2. 组件注解
      • @Component及其衍生注解
        • @Component
        • @Service
        • @Repository
        • @Controller
        • @RestController
    • 3. 依赖注入注解
      • @Autowired
      • @Qualifier
      • @Primary
    • 4. Web相关注解
      • 请求映射注解
        • @RequestMapping
        • HTTP方法特定注解
      • 参数绑定注解
        • @PathVariable
        • @RequestParam
        • @RequestBody
        • @RequestHeader
    • 5. 配置相关注解
      • @Configuration
      • @Bean
      • @Value
      • @ConfigurationProperties
    • 6. 条件注解
      • @Conditional系列
    • 7. 测试注解
      • @SpringBootTest
      • @WebMvcTest
      • @DataJpaTest
    • 8. 事务注解
      • @Transactional
    • 9. 异步处理注解
      • @Async
    • 10. 缓存注解
      • @Cacheable、@CacheEvict、@CachePut
    • 11. 定时任务注解
      • @Scheduled
    • 12. 实际应用示例
      • 实体类
      • Repository层
      • Service层
      • Controller层
    • 总结
    • Spring Boot 注解对比表格


前言

Spring Boot通过大量的注解简化了Java企业级应用的开发,让开发者能够以声明式的方式配置应用程序。本文将系统性地介绍Spring Boot中最重要的注解,帮助开发者深入理解其原理和使用场景。

在这里插入图片描述

1. 核心启动注解

@SpringBootApplication

这是Spring Boot最核心的注解,它是一个组合注解,包含了:

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

等价于以下三个注解的组合:

  • @SpringBootConfiguration:标识这是一个配置类
  • @EnableAutoConfiguration:开启自动配置
  • @ComponentScan:开启组件扫描

@EnableAutoConfiguration

自动配置是Spring Boot的核心特性,它会根据类路径下的依赖自动配置Bean:

@EnableAutoConfiguration
@ComponentScan
public class ManualConfiguration {// 手动配置类
}

@SpringBootConfiguration

继承自@Configuration,用于标识配置类:

@SpringBootConfiguration
public class AppConfig {@Beanpublic MyService myService() {return new MyServiceImpl();}
}

2. 组件注解

@Component及其衍生注解

@Component

最基础的组件注解,标识一个Spring管理的组件:

@Component
public class DataProcessor {public void process(String data) {// 处理逻辑}
}
@Service

业务层组件,语义化更强:

@Service
public class UserService {public User findById(Long id) {// 业务逻辑return new User();}
}
@Repository

数据访问层组件,提供异常转换功能:

@Repository
public class UserRepository {@Autowiredprivate JdbcTemplate jdbcTemplate;public List<User> findAll() {return jdbcTemplate.query("SELECT * FROM users", (rs, rowNum) -> new User(rs.getLong("id"), rs.getString("name")));}
}
@Controller

控制器组件,处理HTTP请求:

@Controller
public class UserController {@GetMapping("/users")public String listUsers(Model model) {// 返回视图名称return "user-list";}
}
@RestController

RESTful控制器,结合了@Controller@ResponseBody

@RestController
@RequestMapping("/api/users")
public class UserRestController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.findAll();}@PostMappingpublic User createUser(@RequestBody User user) {return userService.save(user);}
}

3. 依赖注入注解

@Autowired

自动装配依赖:

@Service
public class OrderService {// 字段注入@Autowiredprivate UserService userService;// 构造函数注入(推荐)private final PaymentService paymentService;@Autowiredpublic OrderService(PaymentService paymentService) {this.paymentService = paymentService;}// Setter注入private EmailService emailService;@Autowiredpublic void setEmailService(EmailService emailService) {this.emailService = emailService;}
}

@Qualifier

当有多个同类型Bean时,指定具体注入哪个:

@Service
public class NotificationService {@Autowired@Qualifier("emailSender")private MessageSender emailSender;@Autowired@Qualifier("smsSender")private MessageSender smsSender;
}

@Primary

标识优先注入的Bean:

@Component
@Primary
public class DefaultMessageSender implements MessageSender {// 默认实现
}

4. Web相关注解

请求映射注解

@RequestMapping

通用请求映射:

@RestController
@RequestMapping("/api/products")
public class ProductController {@RequestMapping(value = "/{id}", method = RequestMethod.GET)public Product getProduct(@PathVariable Long id) {return productService.findById(id);}
}
HTTP方法特定注解
@RestController
@RequestMapping("/api/books")
public class BookController {@GetMappingpublic List<Book> getAllBooks() {return bookService.findAll();}@GetMapping("/{id}")public Book getBook(@PathVariable Long id) {return bookService.findById(id);}@PostMappingpublic Book createBook(@RequestBody Book book) {return bookService.save(book);}@PutMapping("/{id}")public Book updateBook(@PathVariable Long id, @RequestBody Book book) {book.setId(id);return bookService.update(book);}@DeleteMapping("/{id}")public void deleteBook(@PathVariable Long id) {bookService.delete(id);}
}

参数绑定注解

@PathVariable

绑定URL路径参数:

@GetMapping("/users/{userId}/orders/{orderId}")
public Order getOrder(@PathVariable Long userId, @PathVariable Long orderId) {return orderService.findByUserAndId(userId, orderId);
}
@RequestParam

绑定请求参数:

@GetMapping("/search")
public List<Product> searchProducts(@RequestParam String keyword,@RequestParam(defaultValue = "0") int page,@RequestParam(defaultValue = "10") int size) {return productService.search(keyword, page, size);
}
@RequestBody

绑定请求体:

@PostMapping("/users")
public User createUser(@RequestBody User user) {return userService.create(user);
}
@RequestHeader

绑定请求头:

@GetMapping("/profile")
public UserProfile getProfile(@RequestHeader("Authorization") String token) {return userService.getProfileByToken(token);
}

5. 配置相关注解

@Configuration

标识配置类:

@Configuration
public class DatabaseConfig {@Bean@Primarypublic DataSource primaryDataSource() {return DataSourceBuilder.create().url("jdbc:mysql://localhost:3306/primary").build();}@Beanpublic DataSource secondaryDataSource() {return DataSourceBuilder.create().url("jdbc:mysql://localhost:3306/secondary").build();}
}

@Bean

声明Bean:

@Configuration
public class AppConfig {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Bean@ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true")public CacheManager cacheManager() {return new ConcurrentMapCacheManager();}
}

@Value

注入配置值:

@Component
public class AppProperties {@Value("${app.name}")private String appName;@Value("${app.version:1.0}")private String appVersion;@Value("#{systemProperties['user.name']}")private String userName;
}

@ConfigurationProperties

类型安全的配置绑定:

@ConfigurationProperties(prefix = "app.database")
@Component
public class DatabaseProperties {private String url;private String username;private String password;private int maxPoolSize = 10;// getter和setter方法public String getUrl() { return url; }public void setUrl(String url) { this.url = url; }public String getUsername() { return username; }public void setUsername(String username) { this.username = username; }public String getPassword() { return password; }public void setPassword(String password) { this.password = password; }public int getMaxPoolSize() { return maxPoolSize; }public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; }
}

对应的配置文件:

app:database:url: jdbc:mysql://localhost:3306/mydbusername: rootpassword: passwordmax-pool-size: 20

6. 条件注解

@Conditional系列

根据条件创建Bean:

@Configuration
public class ConditionalConfig {@Bean@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")public FeatureService featureService() {return new FeatureServiceImpl();}@Bean@ConditionalOnClass(RedisTemplate.class)public RedisService redisService() {return new RedisServiceImpl();}@Bean@ConditionalOnMissingBeanpublic DefaultService defaultService() {return new DefaultServiceImpl();}
}

7. 测试注解

@SpringBootTest

集成测试:

@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
class UserServiceTest {@Autowiredprivate UserService userService;@Testvoid testCreateUser() {User user = new User("John", "john@example.com");User saved = userService.save(user);assertThat(saved.getId()).isNotNull();assertThat(saved.getName()).isEqualTo("John");}
}

@WebMvcTest

Web层测试:

@WebMvcTest(UserController.class)
class UserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate UserService userService;@Testvoid testGetUser() throws Exception {User user = new User(1L, "John");when(userService.findById(1L)).thenReturn(user);mockMvc.perform(get("/api/users/1")).andExpect(status().isOk()).andExpected(jsonPath("$.name").value("John"));}
}

@DataJpaTest

JPA层测试:

@DataJpaTest
class UserRepositoryTest {@Autowiredprivate TestEntityManager entityManager;@Autowiredprivate UserRepository userRepository;@Testvoid testFindByEmail() {User user = new User("John", "john@example.com");entityManager.persistAndFlush(user);Optional<User> found = userRepository.findByEmail("john@example.com");assertThat(found).isPresent();assertThat(found.get().getName()).isEqualTo("John");}
}

8. 事务注解

@Transactional

事务管理:

@Service
@Transactional
public class OrderService {@Autowiredprivate OrderRepository orderRepository;@Autowiredprivate PaymentService paymentService;@Transactional(rollbackFor = Exception.class)public Order processOrder(Order order) {// 保存订单Order savedOrder = orderRepository.save(order);// 处理支付paymentService.processPayment(order.getPaymentInfo());return savedOrder;}@Transactional(readOnly = true)public List<Order> getOrderHistory(Long userId) {return orderRepository.findByUserId(userId);}
}

9. 异步处理注解

@Async

异步方法执行:

@Service
public class EmailService {@Asyncpublic CompletableFuture<Void> sendEmail(String to, String subject, String body) {// 模拟发送邮件try {Thread.sleep(1000);System.out.println("Email sent to: " + to);} catch (InterruptedException e) {Thread.currentThread().interrupt();}return CompletableFuture.completedFuture(null);}
}@Configuration
@EnableAsync
public class AsyncConfig {@Beanpublic TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(25);executor.setThreadNamePrefix("async-");executor.initialize();return executor;}
}

10. 缓存注解

@Cacheable、@CacheEvict、@CachePut

@Service
public class UserService {@Cacheable(value = "users", key = "#id")public User findById(Long id) {// 从数据库查询return userRepository.findById(id);}@CachePut(value = "users", key = "#user.id")public User update(User user) {return userRepository.save(user);}@CacheEvict(value = "users", key = "#id")public void delete(Long id) {userRepository.deleteById(id);}@CacheEvict(value = "users", allEntries = true)public void clearCache() {// 清除所有缓存}
}

11. 定时任务注解

@Scheduled

定时任务:

@Component
@EnableScheduling
public class ScheduledTasks {@Scheduled(fixedRate = 5000)public void reportCurrentTime() {System.out.println("Current time: " + new Date());}@Scheduled(cron = "0 0 1 * * ?")public void performDailyTask() {// 每天凌晨1点执行System.out.println("Daily task executed");}@Scheduled(fixedDelay = 1000, initialDelay = 2000)public void performTaskWithDelay() {// 延迟2秒后执行,之后每次执行完成后延迟1秒再执行System.out.println("Task with delay executed");}
}

12. 实际应用示例

让我们通过一个完整的用户管理系统来展示这些注解的综合使用:

实体类

@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(nullable = false)private String name;@Column(unique = true, nullable = false)private String email;// 构造函数、getter、setter省略
}

Repository层

@Repository
public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByEmail(String email);List<User> findByNameContaining(String name);
}

Service层

@Service
@Transactional
public class UserService {private final UserRepository userRepository;private final EmailService emailService;public UserService(UserRepository userRepository, EmailService emailService) {this.userRepository = userRepository;this.emailService = emailService;}@Cacheable(value = "users", key = "#id")public User findById(Long id) {return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));}@CachePut(value = "users", key = "#result.id")public User save(User user) {User savedUser = userRepository.save(user);emailService.sendWelcomeEmail(savedUser.getEmail());return savedUser;}@CacheEvict(value = "users", key = "#id")public void delete(Long id) {userRepository.deleteById(id);}
}

Controller层

@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {private final UserService userService;public UserController(UserService userService) {this.userService = userService;}@GetMappingpublic ResponseEntity<List<User>> getAllUsers(@RequestParam(defaultValue = "0") int page,@RequestParam(defaultValue = "10") int size) {Pageable pageable = PageRequest.of(page, size);Page<User> users = userService.findAll(pageable);return ResponseEntity.ok(users.getContent());}@GetMapping("/{id}")public ResponseEntity<User> getUser(@PathVariable Long id) {User user = userService.findById(id);return ResponseEntity.ok(user);}@PostMappingpublic ResponseEntity<User> createUser(@Valid @RequestBody User user) {User savedUser = userService.save(user);return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);}@PutMapping("/{id}")public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {user.setId(id);User updatedUser = userService.save(user);return ResponseEntity.ok(updatedUser);}@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {userService.delete(id);return ResponseEntity.noContent().build();}
}

总结

Spring Boot的注解系统极大地简化了Java企业级应用的开发。通过合理使用这些注解,我们可以:

  1. 简化配置:减少XML配置文件,使用注解进行声明式配置
  2. 提高开发效率:自动装配、自动配置等特性减少了样板代码
  3. 增强可读性:注解直观地表达了代码的意图和功能
  4. 便于测试:丰富的测试注解支持各种测试场景
  5. 功能强大:涵盖了从基础的依赖注入到高级的缓存、异步处理等功能

Spring Boot 注解对比表格

注解标注位置功能
@SpringBootApplicationSpring Boot应用主类标识,包含@Configuration、@EnableAutoConfiguration、@ComponentScan
@EnableAutoConfiguration开启Spring Boot自动配置功能
@SpringBootConfiguration标识配置类,继承自@Configuration
@Component标识Spring管理的通用组件
@Service标识业务层组件,语义化的@Component
@Repository标识数据访问层组件,提供异常转换
@Controller标识MVC控制器组件,返回视图
@RestController标识RESTful控制器,组合@Controller和@ResponseBody
@Autowired字段、方法、构造函数自动依赖注入
@Qualifier字段、方法参数指定注入特定名称的Bean
@Primary类、方法标识优先注入的Bean
@RequestMapping类、方法通用HTTP请求映射
@GetMapping方法GET请求映射,@RequestMapping的简化版
@PostMapping方法POST请求映射,@RequestMapping的简化版
@PutMapping方法PUT请求映射,@RequestMapping的简化版
@DeleteMapping方法DELETE请求映射,@RequestMapping的简化版
@PatchMapping方法PATCH请求映射,@RequestMapping的简化版
@PathVariable方法参数绑定URL路径中的变量
@RequestParam方法参数绑定HTTP请求参数
@RequestBody方法参数绑定HTTP请求体到对象
@RequestHeader方法参数绑定HTTP请求头
@ResponseBody方法、类将方法返回值直接写入HTTP响应体
@Configuration标识配置类,包含@Bean方法
@Bean方法在配置类中声明Bean
@Value字段、方法参数注入配置属性值
@ConfigurationProperties类型安全的配置属性绑定
@ConditionalOnProperty类、方法基于配置属性条件创建Bean
@ConditionalOnClass类、方法基于类存在条件创建Bean
@ConditionalOnMissingBean类、方法当缺少指定Bean时创建Bean
@ConditionalOnBean类、方法当存在指定Bean时创建Bean
@SpringBootTest标识Spring Boot集成测试类
@WebMvcTest标识Web层测试类,只加载MVC相关组件
@DataJpaTest标识JPA层测试类,只加载JPA相关组件
@MockBean字段在测试中创建Mock Bean
@TestPropertySource指定测试配置文件
@Transactional类、方法声明事务边界
@Async方法标识异步执行方法
@EnableAsync开启异步处理功能
@Cacheable方法缓存方法返回结果
@CacheEvict方法清除缓存
@CachePut方法更新缓存
@EnableCaching开启缓存功能
@Scheduled方法标识定时任务方法
@EnableScheduling开启定时任务功能
@Valid方法参数开启JSR-303验证
@Validated类、方法参数开启Spring验证功能
@CrossOrigin类、方法配置跨域资源共享(CORS)
@Profile类、方法指定特定环境下才激活
@Import导入其他配置类
@ComponentScan配置组件扫描路径
@PropertySource指定属性文件位置
@Order类、方法指定组件加载顺序
@EventListener方法标识事件监听器方法
@PostConstruct方法Bean初始化后执行的方法
@PreDestroy方法Bean销毁前执行的方法

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

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

相关文章

Web开发:ABP框架12——中间件Middleware的创建和使用

一、简介中间件可以用于鉴权、日志&#xff0c;拦截器可以用于指定方法或url的业务逻辑处理&#xff0c;两者分工不同&#xff0c;实现效果相似&#xff0c;先执行中间件&#xff0c;后执行拦截器&#xff0c;再到WebAPI接口。二、示例一个Token验证中间件三、代码1.Startup.cs…

京东商品评论如何获取?API接口实战指南

一、API接入准备1. 注册开发者账号访问京东开放平台&#xff1a;前往京东开放平台注册账号&#xff0c;完成企业或个人实名认证。创建应用&#xff1a;在控制台创建应用&#xff0c;获取App Key和App Secret&#xff08;用于签名认证&#xff09;。2. 申请API权限搜索接口&…

leetcode-sql-627变更性别

题目&#xff1a; Salary 表&#xff1a; --------------------- | Column Name | Type | --------------------- | id | int | | name | varchar | | sex | ENUM | | salary | int | --------------------- id 是这个表的主键…

【学习路线】C#企业级开发之路:从基础语法到云原生应用

一、C#基础入门&#xff08;1-2个月&#xff09; &#xff08;一&#xff09;开发环境搭建Visual Studio安装配置 Visual Studio Community&#xff1a;免费版本&#xff0c;功能完整Visual Studio Code&#xff1a;轻量级&#xff0c;跨平台支持JetBrains Rider&#xff1a;专…

Planning Agent:基于大模型的动态规划与ReAct机制,实现复杂问题自适应执行求解

引言 在当今数据驱动的商业环境中&#xff0c;企业面临着日益复杂的决策问题。传统的数据分析工具往往难以应对多步骤、多依赖的复杂问题求解。例如&#xff0c;当企业需要分析"北美市场 Q1-Q2 主要产品的销售增长趋势并识别关键驱动因素"时&#xff0c;传统工具可能…

人该怎样活着呢?55

人该怎样活着呢&#xff1f; A思考现实问题并记录自己的灵感 。【生活的指南针】 &#xff08;20250212&#xff09; a1如何思考&#xff1f; 当有人问他用什么方法得到那么多发现时&#xff0c;牛顿说&#xff1a;“我只不过对于一件事情&#xff0c;总是花很长时间很热…

rtthread - V5.1.0版本 HOOK 钩子函数总结

rtthread - V5.1.0版本 钩子函数 相对于V4.0.3版本做了很大的修改和优化&#xff1a;旧版本 V4.0.3&#xff1a;rt_thread_inited_sethook(thread_inited_hook);rt_thread_deleted_sethook(thread_deleted_hook);rt_scheduler_sethook(scheduler_hook);新版本 V5.1.0&#xff1…

Python特性:装饰器解决数据库长时间断连问题

前言 在基于 Python 的 Web 应用开发里&#xff0c;数据库连接是极为关键的一环。不过&#xff0c;像网络波动、数据库服务器维护这类因素&#xff0c;都可能造成数据库长时间断连&#xff0c;进而影响应用的正常运作。本文将详细介绍怎样运用 retry_on_failure 装饰器来解决数…

疗愈之手的智慧觉醒:Deepoc具身智能如何重塑按摩机器人的触觉神经

疗愈之手的智慧觉醒&#xff1a;Deepoc具身智能如何重塑按摩机器人的触觉神经康复中心的理疗室内&#xff0c;一位运动员正俯卧在治疗床上。机械臂的硅胶触头沿腰背肌群缓缓移动&#xff0c;当传感器捕捉到竖脊肌的异常僵直时&#xff0c;触头自动切换高频震颤模式&#xff1b;…

webpack将组件vue进行编译混淆,并能正常使用编译之后的文件

介绍: 我们在开发的过程中有很多组件都需要复用,特别是我们耗费了好几天时间写出来的组件,比如自己写的表格组件,流程图组件等。总之都是自己不断测试,不断编写耗费了大把的精力写的。直接用到自己的项目中倒是无所谓,如果是把自己写的组件给别人,这里就涉及到自己的劳动…

onenote千年老bug,字体bug (calibri微软雅黑) 的解决

一、如何改这个bug&#xff08;bug是什么在后文&#xff09;一、注意1、有些onenote可能是版本问题&#xff0c;即使提供了设置默认字体的选项&#xff0c;但按教程设置后还是不work&#xff0c;建议升级版本2、亲身测过这个方法是可行的&#xff0c;如果不行&#xff0c;考虑下…

麒麟信安参编的三项软件供应链安全团体标准发布

日前&#xff0c;由中国电子商会正式发布了T/CECC 39—2025《信息安全技术 软件供应链管理规范》、T/CECC 40—2025《信息安全技术 软件供应链开源组件检测要求》以及 T/CECC 41—2025《信息安全技术 软件供应链软件产品检测要素和方法》三项重要团体标准。麒麟信安结合自身在软…

Django ORM系统

1. ORM基础概念1.1 什么是ORM&#xff1f;ORM&#xff08;Object Relational Mapping&#xff0c;对象关系映射&#xff09;是一种编程技术&#xff0c;用于在面向对象编程语言中实现不同类型系统的数据转换。在Django中&#xff0c;ORM充当业务逻辑层和数据库层之间的桥梁。核…

Tailwind CSS中设定宽度和高度的方法

在 Tailwind CSS 中&#xff0c;设定元素的宽度&#xff08;width&#xff09;和高度&#xff08;height&#xff09;有多种方式&#xff0c;涵盖固定值、相对值、响应式调整等。以下是完整的方法分类及示例&#xff1a;一、固定宽度 / 高度类以 4px (0.25rem) 为单位递增&…

Java行为型模式---备忘录模式

备忘录模式基础概念备忘录模式&#xff08;Memento Pattern&#xff09;是一种行为型设计模式&#xff0c;其核心思想是在不破坏封装性的前提下&#xff0c;捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态&#xff0c;以便后续可以将该对象恢复到先前保存的状态…

后端参数校验

前端给后端传输数据&#xff0c;有时候参数需要校验&#xff0c;我们自己写代码会比较麻烦&#xff0c;我们可以使用springboot为我们提供的注解&#xff0c;降低这些没有必要的代码开发。1.引入依赖<dependency><groupId>org.springframework.boot</groupId>…

C++ - 仿 RabbitMQ 实现消息队列--服务端核心模块实现(一)

目录 日志打印工具 实用 Helper 工具 sqlite 基础操作类 字符串操作类 UUID 生成器类 文件基础操作 文件是否存在判断 文件大小获取 读文件 写文件 文件重命名 文件创建/删除 父级目录的获取 目录创建/删除 附录&#xff08;完整代码&#xff09; 日志打印工具 为了便…

C语言:第07天笔记

C语言&#xff1a;第07天笔记 内容提要 循环结构 break与continue 综合案例《猜拳游戏》数组 数组的概念一维数组流程控制 break与continue break 功能&#xff1a; ① 用在switch中&#xff0c;用来跳出switch中的case语句&#xff1b;如果case没有break&#xff0c;可能会产生…

qt 中英文翻译 如何配置和使用

qt 中英文翻译 如何配置和使用 1. 在.pro文件中添加TRANSLATIONS 在你的 .pro 文件&#xff08;比如 HYAC_AAF_HOST.pro&#xff09;中添加&#xff1a; TRANSLATIONS \ zh\_CN.ts en\_US.ts这会告诉Qt项目你要支持中文和英文。 2. 提取可翻译文本&#xff08;生成ts文件&#…

Leetcode 710. 黑名单中的随机数

1.题目基本信息 1.1.题目描述 给定一个整数 n 和一个 无重复 黑名单整数数组 blacklist 。设计一种算法&#xff0c;从 [0, n - 1] 范围内的任意整数中选取一个 未加入 黑名单 blacklist 的整数。任何在上述范围内且不在黑名单 blacklist 中的整数都应该有 同等的可能性 被返…