SpringBoot 常用註解(持續更新)
阿新 • • 發佈:2018-11-14
SpringBoot 常用註解
- @SpringBootApplication
- @Bean
- @ComponentScan
- @ControllerAdvice
- @ExceptionHandler
- @ResponseBody
- @Qualifier
- 注入(@Autowired和@Resource)
@SpringBootApplication
- @SpringBootApplication 註解等價於已預設屬性使用@Configuration、@EnableAutoConfiguration、@ComponentScan。通常使用在有main方法中類的註解
package com.muscleape.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
@Bean
- 產生一個bean的方法,並且交給Spring容器管理;
- 可以理解為用Spring的時候xml裡面的標籤;
- 該註解是用在方法上的,就是用來產生一個Bean;
- 該註解分為兩類:
- 1、使用Bean,即是把已經在xml檔案中配置好的Bean哪裡用,完成屬性、方法的組裝;例如:@Autowired和@Resource,可以通過byTYPE(@Autowired)、byNAME(@Resource)的方式獲取Bean;
- 2、註冊Bean,@Componenet,@Repository,@Controller,@Service,@Configuration這些註解都是把要例項化的物件轉化成一個Bean,放在IOC容器中,等需要使用的時候,會和上面的@Autowired、@Resource配合到一起,把物件、屬性、方法完美組裝;
@Bean(name = "clientbootstrap") public Bootstrap clientBootSrap() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(clientGroup()) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .handler(clientInitializer); return bootstrap; }
@ComponentScan
- 元件掃描。相當於 context:component-scan,如果掃描到有@Component、@Controller、@Service等這些註解的類,就把這些類註冊為bean;
@ControllerAdvice
- 該註解定義全域性異常處理類,通常結合@ExceptionHandler使用;
@ExceptionHandler
- 該註解宣告異常處理方法,通常結合@ControllerAdvice使用;
- handleException()就會處理所有Controller層丟擲的Exception及其子類的異常;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
String handleException(){
return "Exception Deal!";
}
}
@ResponseBody
- 表示該方法的返回結果直接寫入HTTP response body中;
- 一般在非同步獲取資料時使用;
- 在使用@RequestMapping之後,返回值通常解析為跳轉路徑,加上@ResponseBody後返回結果不會被解析為跳轉路徑,而是直接寫入HTTP Response Body中;
@Qualifier
- 當有多個同一型別的Bean時,可以使用@Qualifier("name")來指定;
- 與@Autowired配合使用;
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
注入(@Autowired和@Resource)
- @Autowired與@Resource都可以用來裝配bean. 都可以寫在欄位上,或寫在setter方法上;
- @Autowired預設按型別裝配(這個註解是屬業spring的),預設情況下必須要求依賴物件必須存在,如果要允許null值,可以設定它的required屬性為false,如:@Autowired(required=false) ,如果我們想使用名稱裝配可以結合@Qualifier註解進行使用,如下:
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
- @Resource 是JDK1.6支援的註解,預設按照名稱進行裝配,名稱可以通過name屬性進行指定;@Resource的裝配順序:
- 1、如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則丟擲異常;
- 2、如果指定了name,則從上下文中查詢名稱(id)匹配的bean進行裝配,找不到則丟擲異常;
- 3、如果指定了type,則從上下文中找到型別匹配的唯一bean進行裝配,找不到或者找到多個,都會丟擲異常
- 4、如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配;如果沒有匹配,則回退為一個原始型別進行匹配,如果匹配則自動裝配;