1. 程式人生 > >spring boot常用註解

spring boot常用註解

cati resource resp .profile ring isa selection cor 服務層

@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

spring boot常用註解