天天看點

SpringBoot的常用注解的服用方式

1. @SpringBootApplication

1.1 概述

@SpringBootApplication是SpringBoot應用程式的核心注解,通常用于主類上。它包含了以下三個注解:

  • @Configuration:表示該類是一個配置類,用于定義Spring的配置資訊。
  • @EnableAutoConfiguration:表示啟用自動配置,SpringBoot會根據項目中的依賴自動配置相應的元件。
  • @ComponentScan:表示啟用元件掃描,SpringBoot會自動掃描目前包及其子包下的所有元件。

1.2 使用方法

在主類上添加@SpringBootApplication注解,然後在main方法中調用SpringApplication.run()方法啟動應用程式。

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

1.3 注意事項

  • 主類應放在根包名下,以便能夠掃描到所有的元件,否則會報錯。
  • 可以使用exclude用于排除自動配置的類。

2. @RestController

2.1 概述

@RestController是一個組合注解,用于定義RESTful風格的Web服務。它包含了以下兩個注解:

  • @Controller:表示該類是一個控制器類,用于處理HTTP請求。
  • @ResponseBody:表示将方法傳回值作為HTTP響應體,而不是視圖名稱。

2.2 使用方法

在控制器類上添加@RestController注解,然後在方法上添加相應的HTTP請求映射注解,例如:@GetMapping、@PostMapping等。

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}           

2.3 注意事項

  • 如果需要傳回視圖名稱,可以使用@Controller注解替換@RestController。
  • 如果需要在方法上單獨使用@ResponseBody,可以将@RestController替換為@Controller。

3. @Autowired

3.1 概述

@Autowired用于實作依賴注入。它可以自動裝配Bean,預設按類型裝配,無需手動建立和管理對象。

3.2 使用方法

在需要注入的字段、構造方法或者Setter方法上添加@Autowired注解。

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.getUsers();
    }
}           

3.3 注意事項

  • 如果有多個實作類,可以使用@Qualifier注解指定Bean的名稱。
  • 與之類似的還有@Resource也可以實作依賴注入,隻是注入的方式不同,根據name屬性注入

4. @Component

4.1 概述

@Component用于定義元件。它表示該類是一個Spring管理的Bean,可以被自動掃描和裝配。

4.2 使用方法

在類上添加@Component注解,然後在需要注入的地方使用@Autowired注解。

// 定義元件
@Component
public class UserService {
    public List<User> getUsers() {
        // ...
    }
}

// 使用元件
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.getUsers();
    }
}

           

4.3 注意事項

  • @Component是一個通用注解,還有一些特定場景的注解,例如:@Repository、@Service、@Controller等,但都是依賴于@Component。
  • 如果需要自定義Bean的名稱,可以在@Component注解中添加value屬性。

5. @Configuration

5.1 概述

@Configuration是Spring的核心注解之一,用于定義配置類。它表示該類是一個Java配置類,可以用來替代XML配置檔案。

5.2 使用方法

在類上添加@Configuration注解,然後在方法上添加@Bean注解定義Bean。

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}           

5.3 注意事項

  • 配置類通常與@ComponentScan、@EnableAutoConfiguration等注解一起使用。
  • 如果需要導入其他配置類,可以使用@Import注解。

6. @Bean

6.1 概述

@Bean是Spring的核心注解之一,用于定義Bean。它表示該方法傳回一個Bean,可以被Spring容器管理。

6.2 使用方法

在配置類的方法上添加@Bean注解,然後在需要注入的地方使用@Autowired注解。

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}           

6.3 注意事項

  • 如果需要自定義Bean的名稱,可以在@Bean注解中添加name屬性。
  • 如果需要指定Bean的初始化和銷毀方法,可以使用initMethod和destroyMethod屬性。

7. @RequestMapping

7.1 概述

@RequestMapping用于定義HTTP請求映射。它可以将HTTP請求映射到控制器類或方法上。

7.2 使用方法

在控制器類或方法上添加@RequestMapping注解,然後設定相應的屬性,例如:value、method、produces等。

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id) {
        // ...
    }
}           

7.3 注意事項

  • @RequestMapping是一個通用注解,還有一些特定HTTP方法的注解,例如:@GetMapping、@PostMapping、@PutMapping、@DeleteMapping等。
  • 如果需要處理多個URL,可以在value屬性中使用數組。

8. @PathVariable

8.1 概述

@PathVariable用于擷取URL路徑中的變量。它可以将URL路徑中的變量綁定到方法參數上。

8.2 使用方法

在方法參數上添加@PathVariable注解,然後設定相應的屬性,例如:value、required等。

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/info/{id}/{name}")
    public User getUser(@PathVariable("id") Long id, @PathVariable("name") String userName) {
        // ...
    }
}           

8.3 注意事項

  • 如果方法參數名稱與URL路徑中的變量名稱相同,可以省略value屬性。
  • 如果允許路徑變量不存在,可以将required屬性設定為false。

9. @RequestParam

9.1 概述

@RequestParam是Spring MVC的核心注解之一,用于擷取HTTP請求參數。它可以将HTTP請求參數綁定到方法參數上。

9.2 使用方法

在方法參數上添加@RequestParam注解,然後設定相應的屬性,例如:value、required、defaultValue等。

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/search")
    public List<User> searchUsers(@RequestParam("keyword") String keyword) {
        // ...
    }
}           

9.3 注意事項

  • 如果方法參數名稱與HTTP請求參數名稱相同,可以省略value屬性。
  • 如果允許請求參數不存在,可以将required屬性設定為false。

10. @Value

10.1 概述

@Value用于擷取配置檔案中的屬性值。它可以将配置檔案中的屬性值綁定到字段或方法參數上。

10.2 使用方法

在字段或方法參數上添加@Value注解,然後設定相應的屬性,例如:${property.name}。

@Component
public class AppConfig {
    @Value("${app.name}")
    private String appName;

    public String getAppName() {
        return appName;
    }
}           

10.3 注意事項

  • 如果需要使用預設值,可以在@Value注解中使用:分隔符,例如:${property.name:default}。
  • 如果需要使用占位符,可以在@Value注解中使用#{},例如:#{'Hello, ' + property.name}。

11. @ConfigurationProperties

11.1 概述

@ConfigurationProperties該注解可以直接注入整個類的資料,作用于類

11.2 使用方式

配置檔案application.yml中添加配置

#模拟的類
student:
  name: 張三
  age: 12           

定義配置類StudentInfo,prefix="student"的student對應配置檔案的student,

@Component
@ConfigurationProperties(prefix="student")  // 對應配置檔案的student
public class StudentInfo {
    String name; // 對應配置檔案student下的name
    String age;  // 對應配置檔案student下的age
    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    } 
    public String getAge() { 
      return age; 
    }
    public void setAge(String age) { 
      this.age = age; 
    }
    public void print() {
      System.out.println("name" + name +"age:" + age);
    }
}           

通過@Autowired使用

@Autowired
private StudentInfo student
/**@student的使用*
@Test
void StudentTest()student.print();           

11.3 注意事項

  • 類的字段名必須和配置檔案的字段名一緻
  • 必須要有get和set方法才能注入成功

今天的分享就是這些了,我是Tz,想把我知道的分享給你,如果你喜歡,請點贊關注一下吧~~~