Spring Boot注解詳解

文章目錄

    • 前言
    • 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 中的整數都應該有 同等的可能性 被返…