【SpringBoot】常用註解
@EnableAutoConfiguration
啟動自動裝載:使用了這個註解之後,所有引入的jar的starters都會被自動注入。這個類的設計就是為starter工作的。
@RestController
這個註解專門用於寫RESTful的介面的,裡面集成了@Controller和@ResponseBody註解。
@ResponseBody 這個註解會自動利用預設的Jackson將return的物件序列化成json格式。
@RequestMapping 、@GetMapping、@PostMapping
這些註解主要是配置路由資訊。
@Import、@ImportResource、@Configuration 、@PropertySources
@Configuration :標識當前類是一個Java配置類
@Import:用於手動注入Java config類。
@ImportResource:用於注入XML配置類。
@PropertySources :用於注入properties的配置檔案。
@Value、 @ConfigurationProperties
@Value 這個註解會通過設定的key自動注入 properties檔案裡面配置的Property屬性值。比如
@Value(“${test.name}”) 會自動引入properties檔案裡面配置的test.name的值。
@ConfigurationProperties的作用和@Value類似,但是使用起來稍微麻煩,就不做講解了。
檢視自動載入的類:
If you need to find out what auto-configuration is currently being applied, and why, start your application with the –debug switch. This will enable debug logs for a selection of core loggers and log an auto- configuration report to the console.
@SpringBootApplication
@SpringBootApplication註解等價於以預設屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
這裡有一點需要注意:如果我們需要disable一些特殊的自動裝載的類。可以使用@EnableAutoConfiguration的exclude屬性,去掉自動裝載的類。當然,這個屬性加在@SpringBootApplication註解上也是可以的。
@ComponentScan
元件掃描,如果載入Application這個類上,就不需要引數,自動掃面Application所在的路徑和其下面的包下。不然需要加掃描包路徑。
自動掃描:@Repository、@Service、@Controller、@Component 元件。
@Repository、@Service、@Controller、@Component
元件的標註:在Annotaion配置註解中用@Component來表示一個通用註釋用於說明一個類是一個Spring容器管理的類。即該類已經拉入到Spring的管理中了。而@Controller, @Service, @Repository是@Component的細化,這三個註解比@Component帶有更多的語義,它們分別對應了控制層、服務層、持久層的類。
@Repository註解:用於標註資料訪問元件,即DAO元件
@Service註解:用於標註業務層元件
@Controller註解:用於標註控制層元件(如struts中的action)
@Component註解:泛指元件,當元件不好歸類的時候,我們可以使用這個註解進行標註。
@Profile
這個註解主要加在@Component or @Configuration上面。標識當前profile環境。對於不同的環境可以可以選擇是否載入這些配置。
然後在application.properties中選擇環境,用逗號分隔。
spring.profiles.active=xxxx
@ServletComponentScan
@ServletComponentScan 註解加上後攔截器失效; 去掉後過濾器和監聽器失效
@EnableCaching
開啟Cache快取支援;
@PathVariable:
路徑變數。
@Conditional以及其元註解
@Conditional:滿足特定條件建立一個Bean,SpringBoot就是利用這個特性進行自動配置的;
@ConditionalOnProperty:指定的屬性是否有指定的值;
@ConditionalOnClass:當類路徑下有指定類的條件下
@Autowired和@Resource
@Autowired :預設按照型別載入
@Resource: 預設按照bean的Name進行載入
不過上面兩種都可以通過@qualifier 註解設定注入bean的Name