說起注解,就不得不說到三個最基本的注解:
- 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代碼可以檢查類型安全。
- @AutoConfigureAfter:指定在某個類被spring裝載后裝載。
- @EnableAutoConfiguration:自動配置。
- @Controller 用于標(biāo)記在一個類上,使用它標(biāo)記的類就是一個SpringMVC Controller 對象。分發(fā)處理器將會掃描使用了該注解的類的方法,并檢測該方法是否使用了@RequestMapping 注解。@Controller 只是定義了一個控制器類,而使用@RequestMapping 注解的方法才是真正處理請求的處理器。
- @ResponseBody:表示該方法的返回結(jié)果直接寫入HTTP response body中,一般在異步獲取數(shù)據(jù)時使用,用于構(gòu)建RESTful的api。
- @RestController:@ResponseBody和@Controller的合集。
- @RequestMapping:提供路由信息,負(fù)責(zé)URL到Controller中的具體函數(shù)的映射。
- @ComponentScan:表示將該類自動發(fā)現(xiàn)掃描組件。如果掃描到有@Component、@Controller、@Service、@Autowired、@Configuration等這些注解的類,并注冊為Bean,可以自動收集所有的Spring組件。
- @Inject:等價于默認(rèn)的@Autowired,只是沒有required屬性。
- @Service:一般用于修飾service層的組件。
- @Repository:使用@Repository注解可以確保DAO或者repositories提供異常轉(zhuǎn)譯,這個注解修飾的DAO或者repositories類會被ComponetScan發(fā)現(xiàn)并配置,同時也不需要為它們提供XML配置項。
- @Bean:用@Bean標(biāo)注方法等價于XML中配置的bean。
- @Scope("prototype"): 聲明bean初始化類型,默認(rèn)為單例。
- @PostConstruct:初始化bean執(zhí)行的方法。
- @PreDestory:銷毀bean前執(zhí)行的方法。
- @Qualifier:當(dāng)有多個同一類型的Bean時,可以用@Qualifier(“name”)來指定。與@Autowired配合使用。
- @Value:注入Spring boot application.yml配置的屬性的值。
- @ControllerAdvice:包含@Component??梢员粧呙璧?。統(tǒng)一處理異常。
- @EnableTransactionManagement:開啟事務(wù)管理,確保在啟動類中@component掃描到該類。
- @Transactional:事務(wù)在service層中的使用。
以上是我們常用的一些注解的含義,當(dāng)然我們也可以自定義注解。
在下一節(jié)中我們會將已經(jīng)寫好的接口與數(shù)據(jù)庫進(jìn)行交互,實現(xiàn)一個簡單的從瀏覽器到數(shù)據(jù)庫之間完整的交互。Spring Boot從入門到精通-數(shù)據(jù)庫連接
您的關(guān)注是我最大的動力