說起註解,就不得不說到三個最基本的註解:
- Target:聲明註解用於什麼地方,用的最多的是註解在類上(@Target({ElementType.TYPE}))和方法(@Target({ElementType.METHOD}))上。
- Retention:定義該註解的生命週期
RetentionPolicy這個枚舉類型的常量描述保留註釋的各種策略,它們與元註釋(@Retention)一起指定註釋要保留多長時間。
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
-Documented:Documented註解表明這個註釋是由 javadoc記錄的。
以上是三個公共註解,基本上所有的註解都會繼承這三個註解。
接下來是Spring Boot中常用的一些註解。
- @SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration註解。其中@ComponentScan讓spring Boot掃描到Configuration類並把它加入到程序上下文。
- @Configuration:等同於spring的XML配置文件;使用Java代碼可以檢查類型安全。
- @EnableAutoConfiguration:自動配置。
- @Controller 用於標記在一個類上,使用它標記的類就是一個SpringMVC Controller 對象。分發處理器將會掃描使用了該註解的類的方法,並檢測該方法是否使用了@RequestMapping 註解。@Controller 只是定義了一個控制器類,而使用@RequestMapping 註解的方法纔是真正處理請求的處理器。
- @ResponseBody:表示該方法的返回結果直接寫入HTTP response body中,一般在異步獲取數據時使用,用於構建RESTful的api。
- @RestController:@ResponseBody和@Controller的合集。
- @RequestMapping:提供路由信息,負責URL到Controller中的具體函數的映射。
- @ComponentScan:表示將該類自動發現掃描組件。如果掃描到有@Component、@Controller、@Service、@Autowired、@Configuration等這些註解的類,並註冊爲Bean,可以自動收集所有的Spring組件。
- @Inject:等價於默認的@Autowired,只是沒有required屬性。
- @Service:一般用於修飾service層的組件。
- @Repository:使用@Repository註解可以確保DAO或者repositories提供異常轉譯,這個註解修飾的DAO或者repositories類會被ComponetScan發現並配置,同時也不需要爲它們提供XML配置項。
- @Bean:用@Bean標註方法等價於XML中配置的bean。
- @Scope("prototype"): 聲明bean初始化類型,默認爲單例。
- @PostConstruct:初始化bean執行的方法。
- @PreDestory:銷燬bean前執行的方法。
- @Qualifier:當有多個同一類型的Bean時,可以用@Qualifier(“name”)來指定。與@Autowired配合使用。
- @Value:注入Spring boot application.yml配置的屬性的值。
- @ControllerAdvice:包含@Component。可以被掃描到。統一處理異常。
- @EnableTransactionManagement:開啓事務管理,確保在啓動類中@component掃描到該類。
- @Transactional:事務在service層中的使用。
以上是我們常用的一些註解的含義,當然我們也可以自定義註解。