欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring & Spring Boot 常用注解整理收藏

 更新時(shí)間:2025年05月19日 10:34:46   作者:程序員buddha2080  
注解就像代碼里的便利貼,用來告訴 Spring 框架:這個(gè)類/方法/變量有什么特殊用途,本文分步驟給大家介紹Spring & Spring Boot 常用注解整理,感興趣的朋友一起看看吧

先理解核心概念:什么是注解(Annotation)?

類比:注解就像代碼里的“便利貼”,用來告訴 Spring 框架:“這個(gè)類/方法/變量有什么特殊用途”。
作用:簡(jiǎn)化配置,讓框架自動(dòng)幫你處理一些事情(比如創(chuàng)建對(duì)象、管理依賴、處理請(qǐng)求等)。

第一部分:IOC(控制反轉(zhuǎn))和 DI(依賴注入)

核心思想:把對(duì)象的創(chuàng)建和管理交給 Spring 容器,而不是自己手動(dòng) new 對(duì)象。

注解說明示例
@Component通用組件標(biāo)記,被掃描的類會(huì)納入 Spring 容器管理@Component public class MyComponent { ... }
@Service標(biāo)記服務(wù)層組件,屬于@Component的特化形式@Service public class UserService { ... }
@Repository標(biāo)記數(shù)據(jù)訪問層組件(DAO層),具有數(shù)據(jù)庫異常轉(zhuǎn)譯功能@Repository public class UserDao { ... }
@Controller標(biāo)記控制器組件(Web層)@Controller public class UserController { ... }
@Autowired自動(dòng)注入依賴,默認(rèn)按類型匹配@Autowired private UserService userService;
@Qualifier按名稱指定注入的 Bean@Autowired @Qualifier("userServiceImplA") private UserService service;
@Primary標(biāo)記首選的 Bean(存在多個(gè)同類型 Bean 時(shí)優(yōu)先注入)@Bean @Primary public DataSource primaryDataSource() { ... }
@Scope定義 Bean 的作用域(singleton/prototype等)@Component @Scope("prototype") public class MyPrototypeBean { ... }

1. @Component

作用:告訴 Spring:“這個(gè)類交給你管理,我需要的時(shí)候找你要實(shí)例”。
代碼示例

@Component  // 貼上這個(gè)標(biāo)簽,Spring 就會(huì)自動(dòng)創(chuàng)建 MyComponent 的實(shí)例(Bean)
public class MyComponent {
    public void hello() {
        System.out.println("Hello from MyComponent!");
    }
}

使用場(chǎng)景:通用的工具類、第三方庫的適配類等。

2. @Service, @Repository, @Controller

本質(zhì):它們都是 @Component 的“馬甲”,用途相同,只是名字不同,為了代碼可讀性。

  • @Service:標(biāo)記業(yè)務(wù)邏輯層(如處理用戶注冊(cè)、訂單支付)。
  • @Repository:標(biāo)記數(shù)據(jù)訪問層(如操作數(shù)據(jù)庫)。
  • @Controller:標(biāo)記 Web 控制器(處理 HTTP 請(qǐng)求)。

代碼對(duì)比

@Service
public class UserService {  // 業(yè)務(wù)邏輯層
    public void registerUser(String name) { ... }
}
@Repository
public class UserDao {  // 數(shù)據(jù)訪問層
    public User findUserById(Long id) { ... }
}
@Controller
public class UserController {  // 處理 HTTP 請(qǐng)求
    @GetMapping("/users")
    public String listUsers() { ... }
}

3. @Autowired

作用:讓 Spring 自動(dòng)幫你“注入”依賴的 Bean(類似找人借東西,不用自己造)。
代碼示例

@Service
public class UserService {
    @Autowired  // Spring 會(huì)自動(dòng)找一個(gè) UserDao 的 Bean 注入到這里
    private UserDao userDao;
    public User findUser(Long id) {
        return userDao.findUserById(id);  // 直接使用 userDao,不需要 new UserDao()
    }
}

原理:Spring 會(huì)在容器中查找匹配類型的 Bean,自動(dòng)賦值給 userDao

4. @Qualifier

問題場(chǎng)景:如果有多個(gè)同類型的 Bean,Spring 不知道注入哪一個(gè)。
解決:用 @Qualifier 指定 Bean 的名字。

代碼示例

// 定義兩個(gè)數(shù)據(jù)源
@Component("mysqlDataSource")
public class MySQLDataSource implements DataSource { ... }
@Component("postgresDataSource")
public class PostgresDataSource implements DataSource { ... }
// 使用時(shí)指定名稱
@Service
public class DataService {
    @Autowired
    @Qualifier("mysqlDataSource")  // 明確告訴 Spring 注入名為 "mysqlDataSource" 的 Bean
    private DataSource dataSource;
}

第二部分:Spring MVC(處理 HTTP 請(qǐng)求)

注解說明示例
@RestController組合注解(@Controller + @ResponseBody),用于 REST API@RestController public class ApiController { ... }
@RequestMapping映射 HTTP 請(qǐng)求路徑,可指定 method@RequestMapping(value="/users", method=RequestMethod.GET)
@GetMapping簡(jiǎn)化 GET 請(qǐng)求映射(同理有@PostMapping、@PutMapping等)@GetMapping("/{id}") public User getUser(@PathVariable Long id)
@PathVariable綁定 URL 路徑中的變量@GetMapping("/users/{id}") public User getById(@PathVariable Long id)
@RequestParam綁定請(qǐng)求參數(shù)(支持默認(rèn)值、是否必傳等)@GetMapping("/search") public List<User> search(@RequestParam(defaultValue = "") String keyword)
@RequestBody將請(qǐng)求體內(nèi)容反序列化為 Java 對(duì)象(如 JSON)@PostMapping public User create(@RequestBody User user) { ... }
@ResponseBody將方法返回值序列化為響應(yīng)體(如 JSON)已內(nèi)置在@RestController
@ExceptionHandler處理控制器內(nèi)的特定異常@ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleException() { ... }
@CrossOrigin允許跨域請(qǐng)求@CrossOrigin(origins = "http://example.com")

1. @RestController vs @Controller

  • @Controller:傳統(tǒng) MVC 控制器,返回視圖(如 JSP 頁面)。
  • @RestController:專門用于 REST API,直接返回 JSON 數(shù)據(jù)(內(nèi)部包含 @ResponseBody)。

代碼對(duì)比

// 傳統(tǒng) Controller(返回視圖名,由模板引擎渲染)
@Controller
public class OldController {
    @GetMapping("/hello")
    public String hello() {
        return "hello-page";  // 對(duì)應(yīng) src/main/resources/templates/hello-page.html
    }
}
// REST Controller(返回 JSON)
@RestController
public class ApiController {
    @GetMapping("/user")
    public User getUser() {
        return new User(1, "Alice");  // 自動(dòng)轉(zhuǎn)換為 JSON:{ "id": 1, "name": "Alice" }
    }
}

2. @GetMapping / @PostMapping

作用:簡(jiǎn)化 HTTP 請(qǐng)求映射,替代 @RequestMapping(method=RequestMethod.GET)

代碼示例

@RestController
public class UserController {
    // 處理 GET 請(qǐng)求:http://localhost:8080/users
    @GetMapping("/users")
    public List<User> listUsers() {
        return userService.getAllUsers();
    }
    // 處理 POST 請(qǐng)求:http://localhost:8080/users
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {  // @RequestBody 表示接收 JSON 數(shù)據(jù)
        return userService.saveUser(user);
    }
}

3. @PathVariable 和 @RequestParam

  • @PathVariable:從 URL 路徑中獲取變量(如 /users/123 中的 123)。
  • @RequestParam:從 URL 參數(shù)中獲取值(如 /search?keyword=java 中的 keyword)。

代碼示例

@GetMapping("/users/{id}")  // URL 模板:{id} 是占位符
public User getUserById(@PathVariable Long id) {  // 獲取路徑中的 id
    return userService.findById(id);
}
@GetMapping("/search")
public List<User> searchUsers(@RequestParam String keyword) {  // 獲取參數(shù) ?keyword=xxx
    return userService.search(keyword);
}

第三部分:配置相關(guān)注解

注解說明示例
@Configuration標(biāo)記類為配置類(替代 XML 配置文件)@Configuration public class AppConfig { ... }
@Bean聲明方法返回的對(duì)象作為 Bean 加入容器@Bean public DataSource dataSource() { return new HikariDataSource(); }
@Value注入配置文件中的值@Value("${db.url}") private String dbUrl;
@PropertySource加載指定 properties 文件@Configuration @PropertySource("classpath:custom.properties")
@ConfigurationProperties批量綁定配置文件屬性到對(duì)象(需配合@EnableConfigurationProperties@Component @ConfigurationProperties(prefix="app") public class AppConfig { private String name; ... }
@Profile指定 Bean 生效的環(huán)境@Bean @Profile("dev") public DataSource devDataSource() { ... }

1. @Configuration 和 @Bean

作用:替代 XML 配置文件,手動(dòng)定義 Bean。

代碼示例

@Configuration  // 告訴 Spring:“這是一個(gè)配置類”
public class AppConfig {
    @Bean  // 這個(gè)方法返回的對(duì)象會(huì)被 Spring 管理
    public DataSource dataSource() {
        return new HikariDataSource();  // 手動(dòng)創(chuàng)建一個(gè)數(shù)據(jù)源
    }
}

2. @Value

作用:從配置文件(如 application.properties)中讀取值。

示例

# application.properties
app.name=My Awesome App
database.url=jdbc:mysql://localhost:3306/mydb
@Component
public class AppConfig {
    @Value("${app.name}")  // 注入 app.name 的值
    private String appName;
    @Value("${database.url}")  // 注入數(shù)據(jù)庫 URL
    private String dbUrl;
}

第四部分:Spring Boot 核心注解

注解說明示例
@SpringBootApplication啟動(dòng)類注解(包含@Configuration+@EnableAutoConfiguration+@ComponentScan@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
@EnableAutoConfiguration啟用自動(dòng)配置機(jī)制(通常已包含在@SpringBootApplication中)顯式使用:@SpringBootApplication @EnableAutoConfiguration
@ConditionalOnProperty根據(jù)配置屬性條件化創(chuàng)建 Bean@Bean @ConditionalOnProperty(name="feature.enabled", havingValue="true") public FeatureBean featureBean() { ... }

作用:標(biāo)記啟動(dòng)類,包含三個(gè)核心功能:

  • @Configuration:這是一個(gè)配置類。
  • @EnableAutoConfiguration:開啟自動(dòng)配置(如自動(dòng)配置數(shù)據(jù)庫連接池)。
  • @ComponentScan:自動(dòng)掃描當(dāng)前包及子包下的組件(@Component, @Service 等)。

代碼示例

@SpringBootApplication  // 一切從這里開始
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);  // 啟動(dòng) Spring Boot 應(yīng)用
    }
}

第五部分:數(shù)據(jù)庫和事務(wù)

注解說明示例
@Transactional聲明事務(wù)管理(可加在類或方法上)@Transactional public void updateUser(User user) { ... }
@EntityJPA 實(shí)體類標(biāo)記@Entity public class User { @Id private Long id; ... }
@JpaRepositorySpring Data JPA 的倉庫接口public interface UserRepository extends JpaRepository<User, Long> { ... }

1. @Entity 和 @Id

作用:標(biāo)記 JPA 實(shí)體類(對(duì)應(yīng)數(shù)據(jù)庫表)和主鍵字段。

代碼示例

@Entity  // 告訴 Spring:“這是一個(gè)數(shù)據(jù)庫表對(duì)應(yīng)的實(shí)體類”
public class User {
    @Id  // 標(biāo)記為主鍵
    private Long id;
    private String name;
    // 省略 getter/setter
}

2. @Transactional

作用:聲明事務(wù),確保方法內(nèi)的數(shù)據(jù)庫操作要么全部成功,要么全部回滾。

代碼示例

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Transactional  // 開啟事務(wù)
    public void placeOrder(Order order) {
        orderRepository.save(order);  // 保存訂單
        // 如果這里拋出異常(如庫存不足),整個(gè)事務(wù)會(huì)回滾,訂單不會(huì)被保存
    }
}

第六部分:AOP(面向切面編程)

核心思想:在不修改原有代碼的情況下,統(tǒng)一處理日志、權(quán)限、事務(wù)等橫切關(guān)注點(diǎn)。

注解說明示例
@Aspect聲明切面類@Aspect @Component public class LoggingAspect { ... }
@Pointcut定義切入點(diǎn)表達(dá)式@Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {}
@Before前置通知@Before("serviceMethods()") public void logBefore(JoinPoint jp) { ... }

1. @Aspect 和 @Before

代碼示例

@Aspect   // 告訴 Spring:“這是一個(gè)切面類”
@Component
public class LoggingAspect {
    // 定義切入點(diǎn):攔截所有 Service 層的方法
    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceMethods() {}
    // 前置通知:在方法執(zhí)行前打印日志
    @Before("serviceMethods()")
    public void logBefore(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("準(zhǔn)備執(zhí)行方法:" + methodName);
    }
}

總結(jié):注解的核心作用

場(chǎng)景常用注解類比解釋
管理對(duì)象@Component, @Service告訴 Spring:“這個(gè)類歸你管!”
依賴注入@Autowired, @Qualifier告訴 Spring:“我需要這個(gè),幫我拿!”
處理 HTTP 請(qǐng)求@RestController, @GetMapping告訴 Spring:“這個(gè)方法是處理某個(gè) URL 的!”
讀取配置@Value, @ConfigurationProperties告訴 Spring:“把配置文件的值給我!”
事務(wù)管理@Transactional告訴 Spring:“這個(gè)方法要保證事務(wù)!”

到此這篇關(guān)于Spring &amp; Spring Boot 常用注解整理的文章就介紹到這了,更多相關(guān)Spring Boot 常用注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java如何將BigDecimal類型的值轉(zhuǎn)成double類型

    Java如何將BigDecimal類型的值轉(zhuǎn)成double類型

    這篇文章主要給大家介紹了關(guān)于Java如何將BigDecimal類型的值轉(zhuǎn)成double類型的相關(guān)資料,需要注意精度損失和范圍限制,使用doubleValue方法進(jìn)行轉(zhuǎn)換,并在高精度計(jì)算時(shí)格外小心,需要的朋友可以參考下
    2024-12-12
  • maven中配置項(xiàng)目的jdk版本無效的排查方式

    maven中配置項(xiàng)目的jdk版本無效的排查方式

    這篇文章主要介紹了maven中配置項(xiàng)目的jdk版本無效的排查方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java String.format()的用法

    Java String.format()的用法

    本篇文章主要介紹了JAVA的 String.format()的使用,具有一定的參考價(jià)值,有需要的可以了解一下,希望能夠給你帶來幫助
    2021-11-11
  • SpringBoot 添加本地 jar 文件的操作步驟

    SpringBoot 添加本地 jar 文件的操作步驟

    在平時(shí)我們做項(xiàng)目中,需要用到j(luò)ar包文件,有時(shí)候是不能從maven遠(yuǎn)程倉庫拉取的,這時(shí)候就得考慮用到j(luò)ar文件安裝到本地maven庫中,再添加依賴,今天小編分步驟給大家介紹下SpringBoot 添加本地 jar 文件的流程,一起看看吧
    2021-09-09
  • 解析Neatbeans(常見錯(cuò)誤) build-impl.xml:305: Compile failed

    解析Neatbeans(常見錯(cuò)誤) build-impl.xml:305: Compile failed

    本篇文章是對(duì)Neatbeans(常見錯(cuò)誤) build-impl.xml:305: Compile failed的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-07-07
  • 詳解MyBatis批量插入數(shù)據(jù)Mapper配置文件的寫法

    詳解MyBatis批量插入數(shù)據(jù)Mapper配置文件的寫法

    本篇文章主要介紹了詳解MyBatis批量插入數(shù)據(jù)Mapper文件的寫法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • JavaIO模型中的BIO,NIO和AIO詳解

    JavaIO模型中的BIO,NIO和AIO詳解

    這篇文章主要為大家詳細(xì)介紹了JavaIO模型中的BIO,NIO和AIO,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • 使用jekins自動(dòng)構(gòu)建部署java maven項(xiàng)目的方法步驟

    使用jekins自動(dòng)構(gòu)建部署java maven項(xiàng)目的方法步驟

    這篇文章主要介紹了使用jekins自動(dòng)構(gòu)建部署java maven項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡

    springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡

    這篇文章主要介紹了Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡,想了解負(fù)載均衡的同學(xué)可以參考下
    2021-04-04
  • 通過System.getProperty配置JVM系統(tǒng)屬性

    通過System.getProperty配置JVM系統(tǒng)屬性

    這篇文章主要介紹了通過System.getProperty配置JVM系統(tǒng)屬性,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10

最新評(píng)論