SpringBoot常用注解詳細(xì)整理
前言
Spring Boot常用注解整理
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、@SpringBootApplication
此注解是Spring Boot項目的基石,創(chuàng)建SpringBoot項目的Application時會默認(rèn)加上
@SpringBootApplication public class SpringSecurityApplication{ public static void main(Strings[] args){ SpringApplication.run(SpringSecurityApplication,args); } }
@SpringBootApplication 看作@Configuration,@EnableAutoConfiguration,@ComponentScan 注解的集合
@EnableAutoConfiguration:啟用SpringBoot的自動配置機制
@ComponentScan:掃描被@Component /@Service/@Controller注解的bean,注解默認(rèn)會掃描該類所在的包下所有類
@Configuration:允許在Spring上下文中注冊額外的bean或?qū)肫渌渲妙?/p>
二、@Bean
Bean對象注冊Spring IOC容器與使用bean對象是整個Spring框架的重點,其中@Bean就是一個將方法作為Spring Bean對象注冊的一種方式
package com.edu.fruit; //定義一個接口 public interface Fruit<T>{ //沒有方法 } /* *定義兩個子類 */ package com.edu.fruit; @Configuration public class Apple implements Fruit<Integer>{//將Apple類約束為Integer類型 } package com.edu.fruit; @Configuration public class GinSeng implements Fruit<String>{//將GinSeng 類約束為String類型 } /* *業(yè)務(wù)邏輯類 */ package com.edu.service; @Configuration public class FruitService { @Autowired private Apple apple; @Autowired private GinSeng ginseng; //定義一個產(chǎn)生Bean的方法 @Bean(name="getApple") public Fruit<?> getApple(){ System.out.println(apple.getClass().getName().hashCode); System.out.println(ginseng.getClass().getName().hashCode); return new Apple(); } } /* *測試類 */ @RunWith(BlockJUnit4ClassRunner.class) public class Config { public Config(){ super("classpath:spring-fruit.xml"); } @Test public void test(){ super.getBean("getApple");//這個Bean從哪來, //從上面的@Bean下面的方法中返回的是一個Apple類實例對象 } }
三、@Autowired
@Autowired自動注入注解,最常用的一種注解將對象自動導(dǎo)入到類中,注解自動裝配bean的類
四、Component家族
@Component:通用注解,當(dāng)不知道Bean在哪一層時,可以使用@Component注解標(biāo)注。
@Repository: 對應(yīng)持久層—Dao層的注解,用于操作數(shù)據(jù)庫相關(guān)
@Service: 對應(yīng)服務(wù)層的注解,用來連接Dao層做邏輯處理
@Controller:對應(yīng)Spring MVC控制層,主要接收用戶請求并調(diào)用service返回給前端頁面
五、@RestController
@RestController注解是@Controller注解和@ResponseBody注解的合集,用來返回Json格式給頁面(帶Rest格式的就是返回的Json文本)
六、@Scope
聲明Spring Bean的作用域
@Scope("singleton") public Person personSingleton(){ return new Person(); }
Spring Bean的四種作用域:singleton,prototype,request,session
七、@Configuration
一般聲明配置類,使用@Component或者@Configuration
@Configurantion public class AppConfig{ @Bean public TransferService transferService(){ return new TransferServiceImpl(); } }
八、@RequsetMapping
@RequsetMapping是處理HTTP請求的最通用注解
@RequestMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
八、@GetMapping
一般聲明配置類,使用@Component或者@Configuration
九、@Configuration
@GetMapping 就等價于@RequestMapping(value="/users",method =RequsetMethod.GET)
即使用@GetMapping就相當(dāng)用接收GET方法了
@GetMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
十、@PostMapping
@PostMapping 就等價于@RequestMapping(value="/users",method =RequsetMethod.POST)
即使用@PostMapping就相當(dāng)用接收Post方法了
@PostMapping("/users") public ResponseEntity<List<User>> getAllUsers(){ return userRepository.findAll(); }
十一、@PutMapping
@PutMapping("/users/{userId}")等價于@RequestMapping(value = “/users/{userId}”,method = RequestMethod.PUT)
@PutMapping("/users/{userId}") public ResponseEntity<User> updateUser(@PathVariable (value ="userId")Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest){ ... }
十二、@DeleteMapping
@DeleteMapping("/users/{userId}")等價于@RequestMapping(value ="/users/{userId}",method = RequestMethod.DELETE)
@DeleteMapping("/users/{userId}") public ResponseEntity deleteUser(@PathVariable(value = "userId) Long userId){ ... }
十三、@ParhVariable和@RequestParam
@PathVariable 用于獲取路徑參數(shù), @RequestParam用于獲取查詢參數(shù)
@GetMapping("/users/{userId}/teachers") public List<Teacher> getUserRelatedTeachers(@PathVariable("userId") Long userId,@RequestParam(value = "type",required = false) String type){ ... }
其中@PathVariable是獲取請求中的{userId}值,@RequestParam則是url讀取請求中type的值
比如我們url請求中/users/{123456}/teachers?type=Chinese 則我們在Controller獲取到的就是userId = 123456 , type = Chinese
另在@RequestParam中 value=“參數(shù)名” required = “true/false”(true表示參數(shù)不允許不存在,false表示參數(shù)允許不存在) defaultValue="" 設(shè)置defaultValue時默認(rèn)required為false。
十四、@RequestBody
用于讀取Request請求的body部分,且Content-Type為application/json格式數(shù)據(jù),接收到數(shù)據(jù)后會自動將數(shù)據(jù)綁定在Java對象上,系統(tǒng)會使用HttpMessageConverter來講請求的body中的json字符串轉(zhuǎn)換為Java對象
@PostMapping("/sing-up") public ResponseEntity signUp(@RequsetBody @Valid UserRegisterRequest userRegisterRequest){ userService.save(userRegisterRequest); return ResponseEntity.ok().build()' }
這就是典型的RequestBody在Post請求里進(jìn)行傳輸數(shù)據(jù)當(dāng)后端Controller接收到j(luò)son格式的數(shù)據(jù)后,直接就會生成Java對象映射到UserRegisterRequest類上,這樣就可以直接將userRegisterRequest對象進(jìn)行存儲。順便說一下@Valid注解是用
來驗證數(shù)據(jù)格式是否符合要求,如果符合要求則通過,不符合要求,提示注解中message信息
十五、讀取配置信息
讀取application.yml的注解
wuhan2020: 武漢加油!中國加油! my-profile: name: name email: XXXX@qq.com library: location: dalian books: - name: name1 description: description1 - name: name2 description: description2 - name: name3 description: description3
1.@Value
使用@Value("${property}")讀取簡單的配置信息
@Value("${wuhan2020}") String wuhan2020;
2.@ConfigurationProperties
通過@ConfigurationProperties讀取配置信息并與bean綁定
@Component @ConfigurationProperties(prefix = "library") class LibraryProperties{ @NotEmpty private String location; private List<Book> books; @Data @ToString static class Book{ String name; String description; } }
十六、@Qualifier
當(dāng)有多個同一類型的Bean時,可以用@Qualifier(“name”)來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據(jù)名字進(jìn)行注入,但能進(jìn)行更細(xì)粒度的控制如何選擇候選者,具體使用方式如下:
@Autowired @Qualifier(value = “demoInfoService”) private DemoInfoService demoInfoService;
十七、@MapperScan
spring-boot支持mybatis組件的一個注解,通過此注解指定mybatis接口類的路徑,即可完成對mybatis接口的掃描。
它和@mapper注解是一樣的作用,不同的地方是掃描入口不一樣。@mapper需要加在每一個mapper接口類上面。所以大多數(shù)情況下,都是在規(guī)劃好工程目錄之后,通過@MapperScan注解配置路徑完成mapper接口的注入。
添加mybatis相應(yīng)組建依賴之后。就可以使用該注解。
十八、@CrossOrigin
@CrossOrigin(origins = “”, maxAge = 1000) 這個注解主要是為了解決跨域訪問的問題。這個注解可以為整個controller配置啟用跨域,也可以在方法級別啟用。
十九、@ControllerAdvice
@ControllerAdvice 和 @RestControllerAdvice:通常和@ExceptionHandler、@InitBinder、@ModelAttribute一起配合使用。
@ControllerAdvice 和 @ExceptionHandler 配合完成統(tǒng)一異常攔截處理。
@RestControllerAdvice 是 @ControllerAdvice 和 @ResponseBody的合集,可以將異常以json的格式返回數(shù)據(jù)。
如下面對數(shù)據(jù)異常返回的統(tǒng)一處理。
二十、資源導(dǎo)入注解
@ImportResource @Import @PropertySource 這三個注解都是用來導(dǎo)入自定義的一些配置文件。
@ImportResource(locations={}) 導(dǎo)入其他xml配置文件,需要標(biāo)準(zhǔn)在主配置類上。
導(dǎo)入property的配置文件 @PropertySource指定文件路徑,這個相當(dāng)于使用spring的標(biāo)簽來完成配置項的引入。
@import注解是一個可以將普通類導(dǎo)入到spring容器中做管理
二十一、@Transactional
通過這個注解可以聲明事務(wù),可以添加在類上或者方法上。
在spring boot中 不用再單獨配置事務(wù)管理,一般情況是我們會在servcie層添加了事務(wù)注解,即可開啟事務(wù)。要注意的是,事務(wù)的開啟只能在public 方法上。并且主要事務(wù)切面的回滾條件。正常我們配置rollbackfor exception時 ,如果在方法
里捕獲了異常就會導(dǎo)致事務(wù)切面配置的失效。
總結(jié)
到此這篇關(guān)于SpringBoot常用注解詳細(xì)整理的文章就介紹到這了,更多相關(guān)SpringBoot常用注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatisplus 的SQL攔截器實現(xiàn)關(guān)聯(lián)查詢功能
大家都知道m(xù)ybatisplus不支持關(guān)聯(lián)查詢,后來學(xué)習(xí)研究發(fā)現(xiàn)mybatisplus的SQL攔截器可以實現(xiàn)這一操作,下面小編給大家分享我的demo實現(xiàn)基本的關(guān)聯(lián)查詢功能沒有問題,對mybatisplus關(guān)聯(lián)查詢相關(guān)知識感興趣的朋友一起看看吧2021-06-06Java獲取時間如何將當(dāng)前時間減一天、一月、一年、并格式化
這篇文章主要介紹了Java獲取時間,將當(dāng)前時間減一天、一月、一年,并加以格式化,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09springboot如何使用@ConfigurationProperties封裝配置文件
springboot如何使用@ConfigurationProperties封裝配置文件的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08