spring-boot常用注解

Spring Boot 提供了大量注解來簡化開發(fā),以下是按功能分類的核心注解列表:

1、核心啟動(dòng)注解

1.1@SpringBootApplication
  • 組合注解,包含:
    • @Configuration:標(biāo)記配置類
    • @EnableAutoConfiguration:啟用自動(dòng)配置
    • @ComponentScan:組件掃描

示例:

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

2、Web 開發(fā)注解

2.1 MVC 相關(guān)

  • @RestController
    組合 @Controller+@ResponseBody
    示例:
@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World";
    }
}

2.2 請求映射注解

  • @RequestMapping:通用請求映射
  • @GetMappingGET 請求
  • @PostMappingPOST 請求
  • @PutMappingPUT 請求
  • @DeleteMappingDELETE 請求
  • @PatchMappingPATCH 請求

2.3 參數(shù)處理

  • @PathVariable:獲取路徑參數(shù)
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
  • @RequestParam:獲取查詢參數(shù)
@GetMapping("/search")
public List<User> search(@RequestParam String keyword) { ... }
  • @RequestBody:獲取請求體(JSON/XML
@PostMapping("/users")
public User createUser(@RequestBody User user) { ... }
  • @RequestHeader:獲取請求頭
  • @CookieValue:獲取Cookie

2.4 響應(yīng)處理

  • @ResponseStatus:自定義HTTP狀態(tài)碼
@ResponseStatus(HttpStatus.CREATED)
public User createUser(...) { ... }
  • @ResponseBody:直接返回?cái)?shù)據(jù)(非視圖)

3 、依賴注入相關(guān)

3.1 組件聲明

  • @Component:通用組件
  • @Service:服務(wù)層組件
  • @Repository:數(shù)據(jù)訪問層組件
  • @Controller:控制器組件

3.2 依賴注入

  • @Autowired:自動(dòng)注入(推薦構(gòu)造函數(shù)注入)
    Spring容器在創(chuàng)建當(dāng)前對象的同時(shí)將當(dāng)前類需要依賴的對象通過屬性設(shè)置進(jìn)來,這個(gè)過程也成為"依賴,注入"

這里最好定義的是接口類型,以便日后可以隨時(shí)更換子類為C類,D類..等等(B,C,D...這些類都實(shí)現(xiàn)類該接口).

@Service
public class UserService {
    private final UserRepository userRepo;
    
    @Autowired // Spring 4.3+ 可省略
    public UserService(UserRepository userRepo) {
        this.userRepo = userRepo;
    }
}
  • @Resource:JSR-250標(biāo)準(zhǔn)注入(依賴注入)
    @Resource(name="類名")
    通過向@Resource注解中傳入name參數(shù),參數(shù)值為要加載的類的類名來讓Spring容器完成依賴注入
    需要注意:這里雖然是類名,但是[首字母要小寫]
    要求屬性的名字與類名一致
    @Resource:要求屬性的名字與類名一致
@Resource(name="shirt")   注入Shirt這個(gè)類
private Clothes cloth;

@Resource
private Clothes shirt;    注入Shirt這個(gè)類
  • @Qualifier("summer")
    指定需要引入的組件
@Component("summer")
public class Shirt implements Clothes{
    public void wear(){
        System.out.println("穿上T恤");
    }
}

@Autowired
@Qualifier("summer")
private Clothes clothes;

4、配置相關(guān)注解

4.1 配置屬性

  • @Value:注入簡單值
@Value("${app.name}")
private String appName;
  • @ConfigurationProperties:批量綁定屬性
@ConfigurationProperties(prefix = "app")
public class AppConfig {
    private String name;
    private int version;
    // getters/setters
}

4.2 配置類

  • @Configuration:聲明配置類
  • @PropertySource("classpath:demo/config.properties")
    這里classpath:是用于告知spring容器要從"類路徑"開始,根據(jù)指定的配置文件路徑尋找到
  • @Bean:聲明Bean
@Configuration
@PropertySource("classpath:配置文件路徑")
public class AppConfig {
    @Value("${demo2.student.name}")
    private String name;
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

5、數(shù)據(jù)訪問相關(guān)

5.1 JPA 注解

  • @Entity:實(shí)體類
  • @Table:指定表名
  • @Id:主鍵
  • @GeneratedValue:主鍵生成策略
  • @Column:字段映射
  • @OneToMany/@ManyToOne:關(guān)聯(lián)關(guān)系
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String username;
    
    @OneToMany(mappedBy = "user")
    private List<Order> orders;
}

5.2 事務(wù)管理

  • @Transactional:聲明事務(wù)
@Service
public class UserService {
    @Transactional
    public void updateUser(User user) {
        // 數(shù)據(jù)庫操作
    }
}

6、測試相關(guān)

6.1 測試注解

  • @SpringBootTest:集成測試
  • @WebMvcTest:控制器測試
  • @DataJpaTestJPA測試
  • @MockBean:模擬Bean
@SpringBootTest
class UserServiceTest {
    @Autowired
    private UserService userService;
    
    @MockBean
    private UserRepository userRepository;
    
    @Test
    void testGetUser() {
        // 測試代碼
    }
}

7、定時(shí)任務(wù)

7.1 定時(shí)任務(wù)

  • @EnableScheduling:啟用定時(shí)任務(wù)
  • @Scheduled:定義執(zhí)行計(jì)劃
@Component
public class MyTask {
    @Scheduled(cron = "0 0/5 * * * ?")
    public void doTask() {
        // 每5分鐘執(zhí)行
    }
}

8、AOP 相關(guān)

8.1 AOP 注解

  • @Aspect:聲明切面
  • @Before:前置通知
  • @After:后置通知
  • @Around:環(huán)繞通知
@Aspect
@Component
public class LogAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        // 記錄日志
    }
}

9、緩存相關(guān)

9.1 緩存注解

  • @EnableCaching:啟用緩存
  • @Cacheable:緩存結(jié)果
  • @CacheEvict:清除緩存
  • @CachePut:更新緩存
@Service
public class ProductService {
    @Cacheable("products")
    public Product getProductById(Long id) {
        // 數(shù)據(jù)庫查詢
    }
}

10、Spring Security

10.1 安全注解

  • @EnableWebSecurity:啟用安全配置
  • @PreAuthorize:方法級(jí)權(quán)限控制
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { ... }
@Secured:角色驗(yàn)證
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、@SpringBootApplication 主類(入口類)的注解。(@Configuration,@Enab...
    Timor小先生閱讀 3,496評論 4 5
  • spring-boot使用了大量的注解來進(jìn)行開發(fā), Application類,是spring-boot的啟動(dòng)類, ...
    xjw_2048閱讀 608評論 0 2
  • Spring Boot使用過程中,經(jīng)常需要和很多注解打交道。也是我們常說的注解編程。所以接下來我們對Spri...
    tuacy閱讀 1,689評論 0 11
  • 簡介 SpringBoot基于Spring4.0設(shè)計(jì),不僅繼承了Spring框架原有的優(yōu)秀特性,而且還通過簡化配置...
    一滴礦泉水閱讀 335評論 0 1
  • 注解速覽 配置加載相關(guān) Bean 聲明注解 Bean 注入注解 SpringMVC 注解 MyBatis 注解 配...
    無芽土豆閱讀 1,315評論 0 51

友情鏈接更多精彩內(nèi)容