SpringBoot注解詳解,建議收藏!
一、簡介
基于 SpringBoot 平臺(tái)開發(fā)的項(xiàng)目數(shù)不勝數(shù),與常規(guī)的基于Spring開發(fā)的項(xiàng)目最大的不同之處,SpringBoot 里面提供了大量的注解用于快速開發(fā),而且非常簡單,基本可以做到開箱即用!
那 SpringBoot 為開發(fā)者提供了多少注解呢?我們?cè)撊绾问褂?
針對(duì)此問題,小編特意對(duì)其進(jìn)行了一番整理,內(nèi)容如下,個(gè)人感覺還是比較清晰的,今天我們就一起來整一整每個(gè)注解的含義和用法,以免踩坑!
二、注解總結(jié)
2.1. SpringMVC 相關(guān)注解
- @Controller
通常用于修飾controller層的組件,由控制器負(fù)責(zé)將用戶發(fā)來的URL請(qǐng)求轉(zhuǎn)發(fā)到對(duì)應(yīng)的服務(wù)接口,通常還需要配合注解@RequestMapping使用。
- @RequestMapping
提供路由信息,負(fù)責(zé)URL到Controller中具體函數(shù)的映射,當(dāng)用于方法上時(shí),可以指定請(qǐng)求協(xié)議,比如GET、POST、PUT、DELETE等等。
- @RequestBody
表示請(qǐng)求體的Content-Type必須為application/json格式的數(shù)據(jù),接收到數(shù)據(jù)之后會(huì)自動(dòng)將數(shù)據(jù)綁定到Java對(duì)象上去
- @ResponseBody
表示該方法的返回結(jié)果直接寫入HTTP response body中,返回?cái)?shù)據(jù)的格式為application/json。
比如,請(qǐng)求參數(shù)為json格式,返回參數(shù)也為json格式,示例代碼如下:
/**
* 登錄服務(wù)
*/
@Controller
@RequestMapping("api")
public class LoginController {
/**
* 登錄請(qǐng)求,post請(qǐng)求協(xié)議,請(qǐng)求參數(shù)數(shù)據(jù)格式為json
* @param request
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity login(@RequestBody UserLoginDTO request){
//...業(yè)務(wù)處理
return new ResponseEntity(HttpStatus.OK);
}
}
- @RestController
和@Controller一樣,用于標(biāo)注控制層組件,不同的地方在于:它是@ResponseBody和@Controller的合集,也就是說,在當(dāng)@RestController用在類上時(shí),表示當(dāng)前類里面所有對(duì)外暴露的接口方法,返回?cái)?shù)據(jù)的格式都為application/json,示范代碼如下:
@RestController
@RequestMapping("api")
public class LoginController {
/**
* 登錄請(qǐng)求,post請(qǐng)求協(xié)議,請(qǐng)求參數(shù)數(shù)據(jù)格式為json
* @param request
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public ResponseEntity login(@RequestBody UserLoginDTO request){
//...業(yè)務(wù)處理
return new ResponseEntity(HttpStatus.OK);
}
}
- @RequestParam
用于接收請(qǐng)求參數(shù)為表單類型的數(shù)據(jù),通常用在方法的參數(shù)前面,示范代碼如下:
/**
* 登錄請(qǐng)求,post請(qǐng)求協(xié)議,請(qǐng)求參數(shù)數(shù)據(jù)格式為表單
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity login(@RequestParam(value = "userName",required = true) String userName,
@RequestParam(value = "userPwd",required = true) String userPwd){
//...業(yè)務(wù)處理
return new ResponseEntity(HttpStatus.OK);
}
- @PathVariable
用于獲取請(qǐng)求路徑中的參數(shù),通常用于restful風(fēng)格的api上,示范代碼如下:
/**
* restful風(fēng)格的參數(shù)請(qǐng)求
* @param id
*/
@RequestMapping(value = "queryProduct/{id}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity queryProduct(@PathVariable("id") String id){
//...業(yè)務(wù)處理
return new ResponseEntity(HttpStatus.OK);
}
- @GetMapping
除了@RequestMapping可以指定請(qǐng)求方式之外,還有一些其他的注解,可以用于標(biāo)注接口路徑請(qǐng)求,比如GetMapping用在方法上時(shí),表示只支持get請(qǐng)求方法,等價(jià)于@RequestMapping(value="/get",method=RequestMethod.GET)。
@GetMapping("get")
public ResponseEntity get(){
return new ResponseEntity(HttpStatus.OK);
}
- @PostMapping
用在方法上,表示只支持post方式的請(qǐng)求。
@PostMapping("post")
public ResponseEntity post(){
return new ResponseEntity(HttpStatus.OK);
}
- @PutMapping
用在方法上,表示只支持put方式的請(qǐng)求,通常表示更新某些資源的意思。
@PutMapping("put")
public ResponseEntity put(){
return new ResponseEntity(HttpStatus.OK);
}
- @DeleteMapping
用在方法上,表示只支持delete方式的請(qǐng)求,通常表示刪除某些資源的意思。
@DeleteMapping("delete")
public ResponseEntity delete(){
return new ResponseEntity(HttpStatus.OK);
}
2.2. bean 相關(guān)注解
- @Service
通常用于修飾service層的組件,聲明一個(gè)對(duì)象,會(huì)將類對(duì)象實(shí)例化并注入到bean容器里面。
@Service
public class DeptService {
//具體的方法
}
- @Component
泛指組件,當(dāng)組件不好歸類的時(shí)候,可以使用這個(gè)注解進(jìn)行標(biāo)注,功能類似于于@Service。
@Component
public class DeptService {
//具體的方法
}
- @Repository
通常用于修飾dao層的組件,@Repository注解屬于Spring里面最先引入的一批注解,它用于將數(shù)據(jù)訪問層 (DAO層 ) 的類標(biāo)識(shí)為Spring Bean,具體只需將該注解標(biāo)注在 DAO類上即可,示例代碼如下:
@Repository
public interface RoleRepository extends JpaRepository<Role,Long> {
//具體的方法
}
為什么現(xiàn)在使用的很少呢?
主要是因?yàn)楫?dāng)我們配置服務(wù)啟動(dòng)自動(dòng)掃描dao層包時(shí),Spring會(huì)自動(dòng)幫我們創(chuàng)建一個(gè)實(shí)現(xiàn)類,然后注入到bean容器里面。當(dāng)某些類無法被掃描到時(shí),我們可以顯式的在數(shù)據(jù)持久類上標(biāo)注@Repository注解,Spring會(huì)自動(dòng)幫我們聲明對(duì)象。
- @Bean
相當(dāng)于 xml 中配置 Bean,意思是產(chǎn)生一個(gè) bean 對(duì)象,并交給spring管理,示例代碼如下:
@Configuration
public class AppConfig {
//相當(dāng)于 xml 中配置 Bean
@Bean
public Uploader initFileUploader() {
return new FileUploader();
}
}
- @Autowired
自動(dòng)導(dǎo)入依賴的bean對(duì)象,默認(rèn)時(shí)按照byType方式導(dǎo)入對(duì)象,而且導(dǎo)入的對(duì)象必須存在,當(dāng)需要導(dǎo)入的對(duì)象并不存在時(shí),我們可以通過配置required = false來關(guān)閉強(qiáng)制驗(yàn)證。
@Autowired
private DeptService deptService;
- @Resource
也是自動(dòng)導(dǎo)入依賴的bean對(duì)象,由JDK提供,默認(rèn)是按照byName方式導(dǎo)入依賴的對(duì)象;而@Autowired默認(rèn)時(shí)按照byType方式導(dǎo)入對(duì)象,當(dāng)然@Resource還可以配置成通過byType方式導(dǎo)入對(duì)象。
/**
* 通過名稱導(dǎo)入(默認(rèn)通過名稱導(dǎo)入依賴對(duì)象)
*/
@Resource(name = "deptService")
private DeptService deptService;
/**
* 通過類型導(dǎo)入
*/
@Resource(type = RoleRepository.class)
private DeptService deptService;
- @Qualifier
當(dāng)有多個(gè)同一類型的bean時(shí),使用@Autowired導(dǎo)入會(huì)報(bào)錯(cuò),提示當(dāng)前對(duì)象并不是唯一,Spring不知道導(dǎo)入哪個(gè)依賴,這個(gè)時(shí)候,我們可以使用@Qualifier進(jìn)行更細(xì)粒度的控制,選擇其中一個(gè)候選者,一般于@Autowired搭配使用,示例如下:
@Autowired
@Qualifier("deptService")
private DeptService deptService;
- @Scope
用于生命一個(gè)spring bean的作用域,作用的范圍一共有以下幾種:
- singleton:唯一 bean 實(shí)例,Spring 中的 bean 默認(rèn)都是單例的。
- prototype:每次請(qǐng)求都會(huì)創(chuàng)建一個(gè)新的 bean 實(shí)例,對(duì)象多例。
- request:每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean,該 bean 僅在當(dāng)前 HTTP request 內(nèi)有效。
- session:每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean,該 bean 僅在當(dāng)前 HTTP session 內(nèi)有效。
/**
* 單例對(duì)象
*/
@RestController
@Scope("singleton")
public class HelloController {
}
2.3. JPA 相關(guān)注解
- @Entity和@Table
表明這是一個(gè)實(shí)體類,這兩個(gè)注解一般一塊使用,但是如果表名和實(shí)體類名相同的話,@Table可以省略。
- @Id
表示該屬性字段對(duì)應(yīng)數(shù)據(jù)庫表中的主鍵字段。
- @Column
表示該屬性字段對(duì)應(yīng)的數(shù)據(jù)庫表中的列名,如果字段名與列名相同,則可以省略。
- @GeneratedValue
表示主鍵的生成策略,有四個(gè)選項(xiàng),分別如下:
- AUTO:表示由程序控制,是默認(rèn)選項(xiàng) ,不設(shè)置就是這個(gè)
- IDENTITY:表示由數(shù)據(jù)庫生成,采用數(shù)據(jù)庫自增長,Oracle 不支持這種方式
- SEQUENCE:表示通過數(shù)據(jù)庫的序列生成主鍵ID,MYSQL 不支持
- Table:表示由特定的數(shù)據(jù)庫產(chǎn)生主鍵,該方式有利于數(shù)據(jù)庫的移植
- @SequenceGeneretor
用來定義一個(gè)生成主鍵的序列,它需要與@GeneratedValue聯(lián)合使用才有效,以TB_ROLE表為例,對(duì)應(yīng)的注解配置如下:
@Entity
@Table(name = "TB_ROLE")
@SequenceGenerator(name = "id_seq", sequenceName = "seq_repair",allocationSize = 1)
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主鍵ID,采用【id_seq】序列函數(shù)自增長
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "id_seq")
private Long id;
/* 角色名稱
*/
@Column(nullable = false)
private String roleName;
/**
* 角色類型
*/
@Column(nullable = false)
private String roleType;
}
- @Transient
表示該屬性并非與數(shù)據(jù)庫表的字段進(jìn)行映射,ORM 框架會(huì)將忽略該屬性。
/**
* 忽略該屬性
*/
@Column(nullable = false)
@Transient
private String lastTime;
- @Basic(fetch=FetchType.LAZY)
用在某些屬性上,可以實(shí)現(xiàn)懶加載的效果,也就是當(dāng)用到這個(gè)字段的時(shí)候,才會(huì)裝載這個(gè)屬性,如果配置成fetch=FetchType.EAGER,表示即時(shí)加載,也是默認(rèn)的加載方式!
/**
* 延遲加載該屬性
*/
@Column(nullable = false)
@Basic(fetch = FetchType.LAZY)
private String roleType;
- @JoinColumn
用于標(biāo)注表與表之間關(guān)系的字段,通常與@OneToOne、@OneToMany搭配使用,例如如下:
@Entity
@Table(name = "tb_login_log")
public class LoginLog implements Serializable {
/**
* 查詢登錄的用戶信息
*/
@OneToOne
@JoinColumn(name = "user_id")
private User user;
//...get、set
}
- @OneToOne、@OneToMany和@ManyToOne
這三個(gè)注解,相當(dāng)于hibernate配置文件中的一對(duì)一,一對(duì)多,多對(duì)一配置,比如下面的客戶地址表,通過客戶 ID,實(shí)現(xiàn)客戶信息的查詢。
@Entity
@Table(name="address")
public class AddressEO implements java.io.Serializable {
@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name="customer_id")
private CustomerEO customer;
//...get、set
}
2.4. 配置相關(guān)注解
- @Configuration
表示聲明一個(gè) Java 形式的配置類,Spring Boot 提倡基于 Java 的配置,相當(dāng)于你之前在 xml 中配置 bean,比如聲明一個(gè)配置類AppConfig,然后初始化一個(gè)Uploader對(duì)象。
@Configuration
public class AppConfig {
@Bean
public Uploader initOSSUploader() {
return new OSSUploader();
}
}
- @EnableAutoConfiguration
@EnableAutoConfiguration可以幫助SpringBoot應(yīng)用將所有符合條件的@Configuration配置類,全部都加載到當(dāng)前SpringBoot里,并創(chuàng)建對(duì)應(yīng)配置類的Bean,并把該Bean實(shí)體交給IoC容器進(jìn)行管理。
某些場景下,如果我們想要避開某些配置類的掃描(包括避開一些第三方j(luò)ar包下面的配置,可以這樣處理。
@Configuration
@EnableAutoConfiguration(exclude = { org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})
public class AppConfig {
//具有業(yè)務(wù)方法
}
- @ComponentScan
標(biāo)注哪些路徑下的類需要被Spring掃描,用于自動(dòng)發(fā)現(xiàn)和裝配一些Bean對(duì)象,默認(rèn)配置是掃描當(dāng)前文件夾下和子目錄下的所有類,如果我們想指定掃描某些包路徑,可以這樣處理。
@ComponentScan(basePackages = {"com.xxx.a", "com.xxx.b", "com.xxx.c"})
- @SpringBootApplication
等價(jià)于使用@Configuration、@EnableAutoConfiguration、@ComponentScan這三個(gè)注解,通常用于全局啟動(dòng)類上,示例如下:
@SpringBootApplication
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}
把@SpringBootApplication換成@Configuration、@EnableAutoConfiguration、@ComponentScan這三個(gè)注解,一樣可以啟動(dòng)成功,@SpringBootApplication只是將這三個(gè)注解進(jìn)行了簡化!
- @EnableTransactionManagement
表示開啟事務(wù)支持,等同于 xml 配置方式的:
@SpringBootApplication
@EnableTransactionManagement`
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}
- @Conditional
從 Spring4 開始,可以通過@Conditional注解實(shí)現(xiàn)按條件裝載bean對(duì)象,目前 Spring Boot 源碼中大量擴(kuò)展了@Condition注解,用于實(shí)現(xiàn)智能的自動(dòng)化配置,滿足各種使用場景。下面我給大家列舉幾個(gè)常用的注解:
- @ConditionalOnBean:當(dāng)某個(gè)特定的Bean存在時(shí),配置生效
- @ConditionalOnMissingBean:當(dāng)某個(gè)特定的Bean不存在時(shí),配置生效
- @ConditionalOnClass:當(dāng)Classpath里存在指定的類,配置生效
- @ConditionalOnMissingClass:當(dāng)Classpath里不存在指定的類,配置生效
- @ConditionalOnExpression:當(dāng)給定的SpEL表達(dá)式計(jì)算結(jié)果為true,配置生效
- @ConditionalOnProperty:當(dāng)指定的配置屬性有一個(gè)明確的值并匹配,配置生效
具體的應(yīng)用案例如下:
@Configuration
public class ConditionalConfig {
/**
* 當(dāng)AppConfig對(duì)象存在時(shí),創(chuàng)建一個(gè)A對(duì)象
* @return
*/
@ConditionalOnBean(AppConfig.class)
@Bean
public A createA(){
return new A();
}
/**
* 當(dāng)AppConfig對(duì)象不存在時(shí),創(chuàng)建一個(gè)B對(duì)象
* @return
*/
@ConditionalOnMissingBean(AppConfig.class)
@Bean
public B createB(){
return new B();
}
/**
* 當(dāng)KafkaTemplate類存在時(shí),創(chuàng)建一個(gè)C對(duì)象
* @return
*/
@ConditionalOnClass(KafkaTemplate.class)
@Bean
public C createC(){
return new C();
}
/**
* 當(dāng)KafkaTemplate類不存在時(shí),創(chuàng)建一個(gè)D對(duì)象
* @return
*/
@ConditionalOnMissingClass(KafkaTemplate.class)
@Bean
public D createD(){
return new D();
}
/**
* 當(dāng)enableConfig的配置為true,創(chuàng)建一個(gè)E對(duì)象
* @return
*/
@ConditionalOnExpression("${enableConfig:false}")
@Bean
public E createE(){
return new E();
}
/**
* 當(dāng)filter.loginFilter的配置為true,創(chuàng)建一個(gè)F對(duì)象
* @return
*/
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
@Bean
public F createF(){
return new F();
}
}
- @value
可以在任意 Spring 管理的 Bean 中通過這個(gè)注解獲取任何來源配置的屬性值,比如你在application.properties文件里,定義了一個(gè)參數(shù)變量!
config.name=zhangsan
在任意的bean容器里面,可以通過@Value注解注入?yún)?shù),獲取參數(shù)變量值。
@RestController
public class HelloController {
@Value("${config.name}")
private String config;
@GetMapping("config")
public String config(){
return JSON.toJSONString(config);
}
}
- @ConfigurationProperties
上面@Value在每個(gè)類中獲取屬性配置值的做法,其實(shí)是不推薦的。
一般在企業(yè)項(xiàng)目開發(fā)中,不會(huì)使用那么雜亂無章的寫法而且維護(hù)也麻煩,通常會(huì)一次性讀取一個(gè) Java 配置類,然后在需要使用的地方直接引用這個(gè)類就可以多次訪問了,方便維護(hù),示例如下:
首先,在application.properties文件里定義好參數(shù)變量。
config.name=demo_1
config.value=demo_value_1
然后,創(chuàng)建一個(gè) Java 配置類,將參數(shù)變量注入即可!
@Component
@ConfigurationProperties(prefix = "config")
public class Config {
public String name;
public String value;
//...get、set
}
最后,在需要使用的地方,通過ioc注入Config對(duì)象即可!
- @PropertySource
這個(gè)注解是用來讀取我們自定義的配置文件的,比如導(dǎo)入test.properties和bussiness.properties兩個(gè)配置文件,用法如下:
@SpringBootApplication
@PropertySource(value = {"test.properties","bussiness.properties"})
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}
- @ImportResource
用來加載 xml 配置文件,比如導(dǎo)入自定義的aaa.xml文件,用法如下:
@ImportResource(locations = "classpath:aaa.xml")
@SpringBootApplication
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}
2.5. 異常處理相關(guān)注解
- @ControllerAdvice和@ExceptionHandler
通常組合使用,用于處理全局異常,示例代碼如下:
@ControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionConfig {
private static final Integer GLOBAL_ERROR_CODE = 500;
@ExceptionHandler(value = Exception.class)
@ResponseBody
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
log.error("【統(tǒng)一異常處理器】", e);
ResultMsg<Object> resultMsg = new ResultMsg<>();
resultMsg.setCode(GLOBAL_ERROR_CODE);
if (e instanceof CommonException) {
CommonException ex = (CommonException) e;
if(ex.getErrCode() != 0) {
resultMsg.setCode(ex.getErrCode());
}
resultMsg.setMsg(ex.getErrMsg());
}else {
resultMsg.setMsg(CommonErrorMsg.SYSTEM_ERROR.getMessage());
}
WebUtil.buildPrintWriter(response, resultMsg);
}
}
2.6. 測(cè)試相關(guān)注解
- @ActiveProfiles
一般作用于測(cè)試類上, 用于聲明生效的 Spring 配置文件,比如指定application-dev.properties配置文件。
- @RunWith和@SpringBootTest
一般作用于測(cè)試類上, 用于單元測(cè)試用,示例如下:
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestJunit {
@Test
public void executeTask() {
//測(cè)試...
}
}
三、小結(jié)
整個(gè)篇幅內(nèi)容比較多,比較干,大家在看的過程中,也沒有必要去記住,可以先收藏起來,等到需要用到的時(shí)候,再把它拿出來看看!






