轉自:
一、啟動註解 @SpringBootApplication
<code>@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })public@interfaceSpringBootApplication{}/<code>
查看源碼可發現, @SpringBootApplication是一個複合註解,包含了 @SpringBootConfiguration, @EnableAutoConfiguration`,@ComponentScan` 這三個註解
`@SpringBootConfiguration註解,繼承 @Configuration註解,主要用於加載配置文件 @SpringBootConfiguration繼承自 @Configuration,二者功能也一致,標註當前類是配置類, 並會將當前類內聲明的一個或多個以 @Bean 註解標記的方法的實例納入到 spring 容器中,並且實例名就是方法名。
@EnableAutoConfiguration 註解,開啟自動配置功能 @EnableAutoConfiguration可以幫助 SpringBoot 應用將所有符合條件的 @Configuration配置都加載到當前 SpringBoot 創建並使用的 IoC 容器。藉助於 Spring 框架原有的一個工具類:SpringFactoriesLoader 的支持, @EnableAutoConfiguration可以智能的自動配置功效才得以大功告成
@ComponentScan 註解,主要用於組件掃描和自動裝配 @ComponentScan的功能其實就是自動掃描並加載符合條件的組件或 bean 定義,最終將這些 bean 定義加載到容器中。我們可以通過 basePackages 等屬性指定 @ComponentScan自動掃描的範圍,如果不指定,則默認 Spring 框架實現從聲明 @ComponentScan所在類的 package 進行掃描,默認情況下是不指定的,所以 SpringBoot 的啟動類最好放在 root package 下。
二、Controller 相關注解
@Controller
控制器,處理 http 請求。
@RestController 複合註解
查看 @RestController 源碼
<code>@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic@interfaceRestController{@AliasFor(annotation = Controller.class)String value() default"";}/<code>
從源碼我們知道, @RestController註解相當於 @ResponseBody+ @Controller合在一起的作用, RestController 使用的效果是將方法返回的對象直接在瀏覽器上展示成 json 格式.
@RequestBody
通過 HttpMessageConverter 讀取 Request Body 並反序列化為 Object(泛指)對象
@RequestMapping
@RequestMapping 是 Spring Web 應用程序中最常被用到的註解之一。這個註解會將 HTTP 請求映射到 MVC 和 REST 控制器的處理方法上
@GetMapping 用於將 HTTP get 請求映射到特定處理程序的方法註解
註解簡寫:@RequestMapping(value = "/say",method = RequestMethod.GET) 等價於:@GetMapping(value = "/say")
GetMapping 源碼
<code>@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documented@RequestMapping(method = RequestMethod.GET)public@interfaceGetMapping{}/<code>
是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@PostMapping 用於將 HTTP post 請求映射到特定處理程序的方法註解
<code>@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documented@RequestMapping(method = RequestMethod.POST)public@interfacePostMapping{}/<code>
是 @RequestMapping(method = RequestMethod.POST) 的縮寫
三、取請求參數值
@PathVariable: 獲取 url 中的數據
<code>@Controller@RequestMapping("/User")publicclassHelloWorldController{@RequestMapping("/getUser/{uid}")publicString getUser(@PathVariable("uid")Integer id, Model model) {System.out.println("id:"+id);return"user";}}/<code>
請求示例:http://localhost:8080/User/getUser/123
@RequestParam: 獲取請求參數的值
<code>@Controller@RequestMapping("/User")publicclassHelloWorldController{@RequestMapping("/getUser")publicString getUser(@RequestParam("uid")Integer id, Model model) {System.out.println("id:"+id);return"user";}}/<code>
請求示例:http://localhost:8080/User/getUser?uid=123
四、注入 bean 相關
@Repository DAO 層註解,DAO 層中接口繼承 JpaRepository, 需要在 build.gradle 中引入相關 jpa 的一個 jar 自動加載。
Repository 註解源碼
<code>@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic@interfaceRepository{@AliasFor(annotation = Component.class)String value() default"";}/<code>
<code>@Service@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic@interfaceService{@AliasFor(annotation = Component.class)String value() default"";}/<code>
@Service 是 @Component 註解的一個特例,作用在類上 @Service 註解作用域默認為單例 使用註解配置和類路徑掃描時,被 @Service 註解標註的類會被 Spring 掃描並註冊為 Bean @Service 用於標註服務層組件, 表示定義一個 bean @Service 使用時沒有傳參數,Bean 名稱默認為當前類的類名,首字母小寫 @Service(“serviceBeanId”) 或 @Service(value=”serviceBeanId”) 使用時傳參數,使用 value 作為 Bean 名字 @Scope 作用域註解 @Scope 作用在類上和方法上,用來配置 spring bean 的作用域,它標識 bean 的作用域
@Scope 源碼
<code>@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceScope{@AliasFor("scopeName")String value() default"";@AliasFor("value")String scopeName() default"";ScopedProxyMode proxyMode() defaultScopedProxyMode.DEFAULT;}/<code>
屬性介紹
value
- singleton 表示該 bean 是單例的。(默認)
- prototype 表示該 bean 是多例的,即每次使用該 bean 時都會新建一個對象。
- request 在一次 http 請求中,一個 bean 對應一個實例。
- session 在一個 httpSession 中,一個 bean 對應一個實例。
proxyMode
- DEFAULT 不使用代理。(默認)
- NO 不使用代理,等價於 DEFAULT。
- INTERFACES 使用基於接口的代理 (jdk dynamic proxy)。
- TARGET_CLASS 使用基於類的代理 (cglib)。
@Entity 實體類註解
@Table(name ="數據庫表名"),這個註解也註釋在實體類上,對應數據庫中相應的表。
@Id、@Column 註解用於標註實體類中的字段,pk 字段標註為 @Id,其餘 @Column。
@Bean 產生一個 bean 的方法
@Bean 明確地指示了一種方法,產生一個 bean 的方法,並且交給 Spring 容器管理。支持別名 @Bean("xx-name")
@Autowired 自動導入
@Autowired 註解作用在構造函數、方法、方法參數、類字段以及註解上
@Autowired 註解可以實現 Bean 的自動注入
@Component 把普通 pojo 實例化到 spring 容器中,相當於配置文件中的
雖然有了 @Autowired, 但是我們還是要寫一堆 bean 的配置文件, 相當麻煩, 而 @Component 就是告訴 spring, 我是 pojo 類, 把我註冊到容器中吧, spring 會自動提取相關信息。那麼我們就不用寫麻煩的 xml 配置文件了
五、導入配置文件
@PropertySource 註解
引入單個 properties 文件:
@PropertySource(value = {"classpath : xxxx/xxx.properties"})
引入多個 properties 文件:
@PropertySource(value = {"classpath : xxxx/xxx.properties","classpath : xxxx.properties"})
@ImportResource 導入 xml 配置文件
可以額外分為兩種模式 相對路徑 classpath,絕對路徑(真實路徑)file
注意:單文件可以不寫 value 或 locations,value 和 locations 都可用
相對路徑(classpath)
引入單個 xml 配置文件:@ImportSource("classpath : xxx/xxxx.xml")
引入多個 xml 配置文件:@ImportSource(locations={"classpath : xxxx.xml" , "classpath : yyyy.xml"})
絕對路徑(file)
引入單個 xml 配置文件:@ImportSource(locations= {"file : d:/hellxz/dubbo.xml"})
引入多個 xml 配置文件:@ImportSource(locations= {"file : d:/hellxz/application.xml" , "file : d:/hellxz/dubbo.xml"})
取值:使用 @Value 註解取配置文件中的值
@Value("${properties 中的鍵}") private String xxx;
@Import 導入額外的配置信息
功能類似 XML 配置的,用來導入配置類,可以導入帶有 @Configuration 註解的配置類或實現了 ImportSelector/ImportBeanDefinitionRegistrar。
使用示例
<code>@SpringBootApplication@Import({SmsConfig.class})publicclassDemoApplication{publicstaticvoid main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}/<code>
六、事務註解 @Transactional
在 Spring 中,事務有兩種實現方式,分別是編程式事務管理和聲明式事務管理兩種方式
編程式事務管理:編程式事務管理使用 TransactionTemplate 或者直接使用底層的 PlatformTransactionManager。對於編程式事務管理,spring 推薦使用 TransactionTemplate。聲明式事務管理:建立在 AOP 之上的。其本質是對方法前後進行攔截,然後在目標方法開始之前創建或者加入一個事務,在執行完目標方法之後根據執行情況提交或者回滾事務,通過 @Transactional 就可以進行事務操作,更快捷而且簡單。推薦使用
七、全局異常處理
- @ControllerAdvice 統一處理異常
- @ControllerAdvice 註解定義全局異常處理類
<code>@ControllerAdvicepublicclassGlobalExceptionHandler{}@ExceptionHandler註解聲明異常處理方法@ControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(Exception.class)@ResponseBodyString handleException(){return"Exception Deal!";}}/<code>
(完)
閱讀更多 伊蕊粑粑 的文章