spring-boot注解詳解(一)

spring-boot注解詳解(一)

@SpringBootApplication

@SpringBootApplication = (默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。

  1. @Configuration:提到@Configuration就要提到他的搭檔@Bean。使用這兩個注解就可以創建一個簡單的spring配置類,可以用來替代相應的xml配置文件。
<beans> <bean id = "car" class="com.test.Car"> <property name="wheel" ref = "wheel"></property> </bean> <bean id = "wheel" class="com.test.Wheel"></bean> 
</beans> 

相當于:

@Configuration 
public class Conf { @Bean public Car car() { Car car = new Car(); car.setWheel(wheel()); return car; } @Bean  public Wheel wheel() { return new Wheel(); } 
}

@Configuration的注解類標識這個類可以使用Spring IoC容器作為bean定義的來源。@Bean注解告訴Spring,一個帶有@Bean的注解方法將返回一個對象,該對象應該被注冊為在Spring應用程序上下文中的bean。
2、@EnableAutoConfiguration:能夠自動配置spring的上下文,試圖猜測和配置你想要的bean類,通常會自動根據你的類路徑和你的bean定義自動配置。
3、@ComponentScan:會自動掃描指定包下的全部標有@Component的類,并注冊成bean,當然包括@Component下的子注解@Service,@Repository,@Controller。

@EnableTransactionManagement

@EnableTransactionManagement 開啟事務支持后,然后在訪問數據庫的Service方法上添加注解 @Transactional 便可。
關于事務管理器,不管是JPA還是JDBC等都實現自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依賴,框架會默認注入 DataSourceTransactionManager 實例。如果你添加的是 spring-boot-starter-data-jpa 依賴,框架會默認注入 JpaTransactionManager 實例。
你可以在啟動類中添加如下方法,Debug測試,就能知道自動注入的是 PlatformTransactionManager 接口的哪個實現類。


@EnableTransactionManagement // 啟注解事務管理,等同于xml配置方式的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication {@Beanpublic Object testBean(PlatformTransactionManager platformTransactionManager){System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());return new Object();}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}

這些SpringBoot為我們自動做了,這些對我們并不透明,如果你項目做的比較大,添加的持久化依賴比較多,我們還是會選擇人為的指定使用哪個事務管理器。
代碼如下:

@EnableTransactionManagement
@SpringBootApplication
public class ProfiledemoApplication {// 其中 dataSource 框架會自動為我們注入@Beanpublic PlatformTransactionManager txManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Beanpublic Object testBean(PlatformTransactionManager platformTransactionManager) {System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());return new Object();}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}
}

在Spring容器中,我們手工注解@Bean 將被優先加載,框架不會重新實例化其他的 PlatformTransactionManager 實現類。

然后在Service中,被 @Transactional 注解的方法,將支持事務。如果注解在類上,則整個類的所有方法都默認支持事務。

對于同一個工程中存在多個事務管理器要怎么處理,請看下面的實例,具體說明請看代碼中的注釋。

@EnableTransactionManagement // 開啟注解事務管理,等同于xml配置文件中的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication implements TransactionManagementConfigurer {@Resource(name="txManager2")private PlatformTransactionManager txManager2;// 創建事務管理器1@Bean(name = "txManager1")public PlatformTransactionManager txManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}// 創建事務管理器2@Bean(name = "txManager2")public PlatformTransactionManager txManager2(EntityManagerFactory factory) {return new JpaTransactionManager(factory);}// 實現接口 TransactionManagementConfigurer 方法,其返回值代表在擁有多個事務管理器的情況下默認使用的事務管理器@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {return txManager2;}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}}
@Component
public class DevSendMessage implements SendMessage {// 使用value具體指定使用哪個事務管理器@Transactional(value="txManager1")@Overridepublic void send() {System.out.println(">>>>>>>>Dev Send()<<<<<<<<");send2();}// 在存在多個事務管理器的情況下,如果使用value具體指定// 則默認使用方法 annotationDrivenTransactionManager() 返回的事務管理器@Transactionalpublic void send2() {System.out.println(">>>>>>>>Dev Send2()<<<<<<<<");}}

注:
如果Spring容器中存在多個 PlatformTransactionManager 實例,并且沒有實現接口 TransactionManagementConfigurer 指定默認值,在我們在方法上使用注解 @Transactional 的時候,就必須要用value指定,如果不指定,則會拋出異常。

對于系統需要提供默認事務管理的情況下,實現接口 TransactionManagementConfigurer 指定。

對有的系統,為了避免不必要的問題,在業務中必須要明確指定 @Transactional 的 value 值的情況下。不建議實現接口 TransactionManagementConfigurer,這樣控制臺會明確拋出異常,開發人員就不會忘記主動指定。

@Controller

@Controller用于標記在一個類上,使用它標記的類就是一個SpringMvc Controller對象,分發處理器會掃描使用該注解的類的方法,并檢測該方法是否使用了@RequestMapping注解。
@Controller只是定義了一個控制器類,而使用@RequestMapping注解的方法才是處理請求的處理器。
@Controller標記在一個類上還不能真正意義上說它就是SpringMvc的控制器,應為這個時候Spring還不認識它,這個時候需要把這個控制器交給Spring來管理。有兩種方式可以管理:

<!--基于注解的裝配-->
<!--方式一-->
<bean class="com.HelloWorld"/>
<!--方式二-->
<!--路徑寫到controller的上一層-->
<context:component-scan base-package="com"/>

Action層:

package com;
@Controller
public class HelloWorld{@RequestMapping(value="/showRegUser")public String printHello() {return "hello";}@Autowriedprivate IocSerevce service;public void add(){service.add();}
}

component-scan默認掃描的注解類型是@Component,不過,在@Component的語義基礎之上細化為@Reposity,@Service,@Controller.
有一個use-defaultbao’i-filters屬性,屬性默認是true,表示會掃描抱下所有的標有@Component的類,并注冊為bean,也就是@Component的子注解@Service,@reposity等
如果只想掃描包下的@Controller或其他內容,則設置use-default-filters屬性為false,表示不再按照scan指定的包進行掃描,而是按照指定包進行掃描

<context:component-scan base-package="com" user-default-filters="false"><context:include-filter type="regex" expression="com.tan.*"/>
</context:component-scan>

當沒有設置use-default-filters屬性或屬性為true時,表示基于base-package包下指定掃描的具體路徑。

@RequestMapping

RequestMapping是一個用來處理請求地址映射的注解,可用于類或方法上。用于類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。

RequestMapping注解有六個屬性,下面我們把她分成三類進行說明。

1.value, method;

value: 指定請求的實際地址,指定的地址可以是URI Template 模式(后面將會說明);

method: 指定請求的method類型, GET、POST、PUT、DELETE等;
默認 RequestMapping(“url”)即為value的值;
顯式說明 RequestMapping(value=”url”)

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {private AppointmentBook appointmentBook;@Autowiredpublic AppointmentsController(AppointmentBook appointmentBook) {this.appointmentBook = appointmentBook;}@RequestMapping(method = RequestMethod.GET)public Map<String, Appointment> get() {return appointmentBook.getAppointmentsForToday();}@RequestMapping(value="/{day}", method = RequestMethod.GET)public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {return appointmentBook.getAppointmentsForDay(day);}@RequestMapping(value="/new", method = RequestMethod.GET)public AppointmentForm getNewForm() {return new AppointmentForm();}@RequestMapping(method = RequestMethod.POST)public String add(@Valid AppointmentForm appointment, BindingResult result) {if (result.hasErrors()) {return "appointments/new";}appointmentBook.addAppointment(appointment);return "redirect:/appointments";}
}

value的url值為以下三類:
A) 可以指定為普通的具體值;

B) 可以指定為含有某變量的一類值(URI Template Patterns with Path Variables);

C) 可以指定為含正則表達式的一類值( URI Template Patterns with Regular Expressions);

example B)@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {Owner owner = ownerService.findOwner(ownerId);  model.addAttribute("owner", owner);  return "displayOwner"; 
}
example C)@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")public void handle(@PathVariable String version, @PathVariable String extension) {    // ...}
}

2.consumes,produces;

consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;

produces: 指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    // implementation omitted
}
方法僅處理request Content-Type為“application/json”類型的請求。produces的樣例:@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    // implementation omitted
}

方法僅處理request請求中Accept頭中包含了”application/json”的請求,同時暗示了返回的內容類型為application/json;

3.params,headers;

params: 指定request中必須包含某些參數值是,才讓該方法處理。

headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    // implementation omitted}
}

僅處理請求中包含了名為“myParam”,值為“myValue”的請求;
headers的樣例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    // implementation omitted}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250175.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250175.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250175.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

前端基礎-jQuery的優點以及用法

一、jQuery介紹 jQuery是一個輕量級的、兼容多瀏覽器的JavaScript庫。jQuery使用戶能夠更方便地處理HTML Document、Events、實現動畫效果、方便地進行Ajax交互&#xff0c;能夠極大地簡化JavaScript編程。它的宗旨就是&#xff1a;“Write less, do more.“二、jQuery的優勢 一…

[pytorch、學習] - 3.12 權重衰減

參考 3.12 權重衰減 本節介紹應對過擬合的常用方法 3.12.1 方法 正則化通過為模型損失函數添加懲罰項使學出的模型參數更小,是應對過擬合的常用手段。 3.12.2 高維線性回歸實驗 import torch import torch.nn as nn import numpy as np import sys sys.path.append("…

Scapy之ARP詢問

引言 校園網中&#xff0c;有同學遭受永恒之藍攻擊&#xff0c;但是被殺毒軟件查下&#xff0c;并知道了攻擊者的ip也是校園網。所以我想看一下&#xff0c;這個ip是PC&#xff0c;還是路由器。 在ip視角&#xff0c;路由器和pc沒什么差別。 實現 首先是構造arp報文&#xff0c…

spring-boot注解詳解(二)

ResponseBody 作用&#xff1a; 該注解用于將Controller的方法返回的對象&#xff0c;通過適當的HttpMessageConverter轉換為指定格式后&#xff0c;寫入到Response對象的body數據區。使用時機&#xff1a; 返回的數據不是html標簽的頁面&#xff0c;而是其他某種格式的數據時…

轉:org.apache.maven.archiver.MavenArchiver.getManifest錯誤

eclipse導入新的maven項目時&#xff0c;pom.xml第一行報錯&#xff1a; org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration) 解決辦法&#xff1a; 1、Help——>Install …

Codeforces Round #524 Div. 2 翻車記

A&#xff1a;簽到。room里有一個用for寫的&#xff0c;hack了一發1e8 1&#xff0c;結果用了大概600ms跑過去了。慘絕人寰。 #include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorith…

[pytorch、學習] - 3.13 丟棄法

參考 3.13 丟棄法 過擬合問題的另一種解決辦法是丟棄法。當對隱藏層使用丟棄法時,隱藏單元有一定概率被丟棄。 3.12.1 方法 3.13.2 從零開始實現 import torch import torch.nn as nn import numpy as np import sys sys.path.append("..") import d2lzh_pytorc…

springboot---request 中Parameter,Attribute區別

HttpServletRequest類既有getAttribute()方法&#xff0c;也由getParameter()方法&#xff0c;這兩個方法有以下區別&#xff1a; &#xff08;1&#xff09;HttpServletRequest類有setAttribute()方法&#xff0c;而沒有setParameter()方法 &#xff08;2&#xff09;當兩個…

Python之令人心煩意亂的字符編碼與轉碼

ASC-II碼&#xff1a;英文1個字節&#xff08;8 byte&#xff09;&#xff0c;不支持中文&#xff1b; 高大上的中國&#xff0c;擴展出自己的gbk、gb2312、gb2318等字符編碼。 由于各個國家都有自己的編碼&#xff0c;于是就需要統一的編碼形式用于國際流傳&#xff0c;防止亂…

[pytorch、學習] - 4.1 模型構造

參考 4.1 模型構造 讓我們回顧以下多重感知機的簡潔實現中包含單隱藏層的多重感知機的實現方法。我們首先構造Sequential實例,然后依次添加兩個全連接層。其中第一層的輸出大小為256,即隱藏層單元個數是256;第二層的輸出大小為10,即輸出層單元個數是10. 4.1.1 繼承Module類來…

springboot---基本模塊詳解

概述 1.基于Spring框架的“約定優先于配置&#xff08;COC&#xff09;”理念以及最佳實踐之路。 2.針對日常企業應用研發各種場景的Spring-boot-starter自動配置依賴模塊&#xff0c;且“開箱即用”&#xff08;約定spring-boot-starter- 作為命名前綴&#xff0c;都位于org.…

第二課 運算符(day10)

第二課 運算符(day10) 一、運算符 結果是值 算數運算 a 10 * 10 賦值運算 a a 1 a1 結果是布爾值 比較運算 a 1 > 5 邏輯運算 a 1>6 or 11 成員運算 a "蚊" in "鄭建文" 二、基本數據類型 1、數值…

[pytorch、學習] - 4.2 模型參數的訪問、初始化和共享

參考 4.2 模型參數的訪問、初始化和共享 在3.3節(線性回歸的簡潔實現)中,我們通過init模塊來初始化模型的參數。我們也介紹了訪問模型參數的簡單方法。本節將深入講解如何訪問和初始化模型參數,以及如何在多個層之間共享同一份模型參數。 import torch from torch import nn…

spring-boot注解詳解(三)

1.SpringBoot/spring SpringBootApplication: 包含Configuration、EnableAutoConfiguration、ComponentScan通常用在主類上&#xff1b; Repository: 用于標注數據訪問組件&#xff0c;即DAO組件&#xff1b; Service: 用于標注業務層組件&#xff1b; RestController: 用于…

IEnumerableT和IQueryableT區分

哎&#xff0c;看了那么多&#xff0c;這個知識點還是得開一個文章 IQueryable和IEnumerable都是延時執行(Deferred Execution)的&#xff0c;而IList是即時執行(Eager Execution) IQueryable和IEnumerable在每次執行時都必須連接數據庫讀取&#xff0c;而IList讀取一次后&…

表的轉置 行轉列: DECODE(Oracle) 和 CASE WHEN 的異同點

異同點 都可以對表行轉列&#xff1b;DECODE功能上和簡單Case函數比較類似&#xff0c;不能像Case搜索函數一樣&#xff0c;進行更復雜的判斷在Case函數中&#xff0c;可以使用BETWEEN, LIKE, IS NULL, IN, EXISTS等等&#xff08;也可以使用NOT IN和NOT EXISTS&#xff0c;但是…

[pytorch、學習] - 4.4 自定義層

參考 4.4 自定義層 深度學習的一個魅力在于神經網絡中各式各樣的層,例如全連接層和后面章節將要用介紹的卷積層、池化層與循環層。雖然PyTorch提供了大量常用的層,但有時候我們依然希望自定義層。本節將介紹如何使用Module來自定義層,從而可以被重復調用。 4.4.1 不含模型參…

樹的存儲

父親表示法 顧名思義&#xff0c;就是只記錄每個結點的父結點。 int n; int p[MAX_N]; // 指向每個結點的父結點 孩子表示法 如上&#xff0c;就是只記錄每個結點的子結點。 int n; int cnt[MAX_N]; // 記錄每個結點的子結點的數量 int p[MAX_N][MAX_CNT]; // 指向每個結點的子…

spring-boot注解詳解(四)

repository repository跟Service,Compent,Controller這4種注解是沒什么本質區別,都是聲明作用,取不同的名字只是為了更好區分各自的功能.下圖更多的作用是mapper注冊到類似于以前mybatis.xml中的mappers里. 也是因為接口沒辦法在spring.xml中用bean的方式來配置實現類吧(接口…

令人叫絕的EXCEL函數功能

http://club.excelhome.net/thread-166725-1-1.html https://wenku.baidu.com/view/db319da0bb0d4a7302768e9951e79b8969026864.html轉載于:https://www.cnblogs.com/cqufengchao/articles/9150401.html