安徽省外經(jīng)建設(shè)集團(tuán)有限公司網(wǎng)站b站推廣
一、什么是Spring Boot
Spring Boot是一個(gè)快速開發(fā)框架,快速的將一些常用的第三方依賴整合(通過Maven子父親工程的方式),簡化xml配置,全部采用注解形式,內(nèi)置Http服務(wù)器(Jetty和Tomcat),最終以Java應(yīng)用程序進(jìn)行執(zhí)行。
二、Spring常用注解
Spring常用注解(全)
三、Spring Boot常用注解
1、@SpringBootApplication
替代 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan
2、@ImportAutoConfiguration
導(dǎo)入配置類,一般做測試的時(shí)候使用,正常優(yōu)先使用@EnableAutoConfiguration
3、@SpringBootConfiguration
替代@Configuration
4、@ImportResource
將資源導(dǎo)入容器
5、@PropertySource
導(dǎo)入properties文件
6、PropertySources
@PropertySource 的集合
7、@Role
bean角色定義為ROLE_APPLICATION(默認(rèn)值)、ROLE_SUPPORT(輔助角色)、ROLE_INFRASTRUCTURE(后臺角色,用戶無感)
8、@Scope
指定bean的作用域,默認(rèn)singleton,其它包括prototype、request、session、globalSession
9、@Lazy
使bean懶加載,取消bean預(yù)初始化。
10、@Primary
自動(dòng)裝配時(shí)當(dāng)出現(xiàn)多個(gè)Bean候選者時(shí),被注解為@Primary的Bean將作為首選者,否者將拋出異常。
11、@Profile
指定Bean在哪個(gè)環(huán)境下被激活
12、@DependsOn
依賴的bean注冊完成,才注冊當(dāng)前類,依賴bean不存在會(huì)報(bào)錯(cuò)。用于控制bean加載順序
13、@PostConstruct
bean的屬性都注入完畢后,執(zhí)行注解標(biāo)注的方式進(jìn)行初始化工作
14、@Autowired
默認(rèn)按類型裝配,如果我們想使用按名稱裝配,可以結(jié)合@Qualifier注解一起使用。
15、@Lookup
根據(jù)方法返回的類型,去容器中撈出對應(yīng)
16、@Qualifier
申明bean名字,且可以按bean名字加載bean
17、@Required
檢查bean的屬性setXXX()方法,要求屬性砸死配置階段必須已配置
18、@Description
添加bean的文字描述
19、@EnableAspectConfiguration
啟動(dòng)AspectJ自動(dòng)配置
20、EnableLoadTimeWeaving
啟動(dòng)類加載器動(dòng)態(tài)增強(qiáng)功能,使用instrumentation實(shí)現(xiàn)
21、@AutoConfigurationPackage
包含該注解的package會(huì)被AutoConfigurationPackages注冊
22、@AutoConfigureBefore
在指定配置類初始化前加載
23、@AutoConfigureAfter
在指定配置類初始化后加載
24、@AutoConfigureOrder
指定配置類初始化順序,越小初始化越早
25、@ModelAttribute
@ModelAttribute注解可被應(yīng)用在方法和方法參數(shù)上。
(1)對方法使用 @ModelAttribute 注解:
注解在方法上的@ModelAttribute說明了方法的作用是用于添加一個(gè)或多個(gè)屬性到model上。這樣的方法能接受與@RequestMapping注解相同的參數(shù)類型,只不過不能直接被映射到具體的請求上。
@ModelAttribute 方法會(huì)先被調(diào)用。
在同一個(gè)控制器中,注解了@ModelAttribute的方法實(shí)際上會(huì)在@RequestMapping方法之前被調(diào)用。以下是幾個(gè)例子:
@Controller
public class ModelAttributeController {@ModelAttributepublic void init(Model model) {System.out.println("@RequestMapping方法");}@RequestMapping("/model-attribute")public String get() {System.out.println("@ModelAttribute方法");return "model-attribute";}}
可以使用 @ModelAttribute 標(biāo)注的方法來設(shè)置其他 @ReqeustMapping 方法的公用參數(shù)
使用 @ModelAttribute(“key”) 來顯示指定屬性名。
(2)@ModelAttribute 和 @RequestMapping 注解在同一個(gè)方法上
如果 @ModelAttribute 和 @RequestMapping 注解在同一個(gè)方法上,那么代表給這個(gè)請求單獨(dú)設(shè)置 Model
參數(shù)。此時(shí)返回的值是 Model 的參數(shù)值,而不是跳轉(zhuǎn)的地址。跳轉(zhuǎn)的地址是根據(jù)請求的 url 自動(dòng)轉(zhuǎn)換而來的。比如下面的例子中跳轉(zhuǎn)頁面不是
HelloWorld.jsp 而是 model-attribute.jsp。并且參數(shù)只有在 model-attribute.jsp
中能夠取得,而 demo.jsp 中不能取得。
(3)在方法參數(shù)上使用 @ModelAttribute 注解
① 數(shù)據(jù)綁定
注解在方法參數(shù)上的@ModelAttribute說明了該方法參數(shù)的值將由model中取得。如果model中找不到,那么該參數(shù)會(huì)先被實(shí)例化,然后被添加到model中。在model中存在以后,請求中所有名稱匹配的參數(shù)都會(huì)填充到該參數(shù)中。這在Spring
MVC中被稱為數(shù)據(jù)綁定,一個(gè)非常有用的特性,節(jié)約了你每次都需要手動(dòng)從表格數(shù)據(jù)中轉(zhuǎn)換這些字段數(shù)據(jù)的時(shí)間。
② 和 BindingResult 配合使用
使用 @ModelAttribute 進(jìn)行數(shù)據(jù)綁定之后,可以使用 BindingResult 來返回?cái)?shù)據(jù)驗(yàn)證結(jié)果。數(shù)據(jù)驗(yàn)證可以使用
hibernate validation 的 @Valid 標(biāo)簽或者 spring Validator 校驗(yàn)機(jī)制的 @Validated
配合 BindingResult 使用。 或者自定義校驗(yàn)器來返回 BindingResult 對象來進(jìn)行校驗(yàn)。你可以通過Spring的
表單標(biāo)簽來在同一個(gè)表單上顯示錯(cuò)誤信息。
@Valid 校驗(yàn)器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) {if (result.hasErrors()) {return "petForm";}// ...}
@Validated 校驗(yàn)器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@Validated @ModelAttribute("pet") Pet pet, BindingResult result) {if (result.hasErrors()) {return "petForm";}// ...}
自定義校驗(yàn)器:
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {// 自己編寫一個(gè)校驗(yàn)方法來處理 result 對象new PetValidator().validate(pet, result);if (result.hasErrors()) {return "petForm";}// ...}
四、選擇器
@Conditional,當(dāng)指定的條件都滿足時(shí),組件才被注冊
@ConditionalOnBean,指定bean在上下文中時(shí),才注冊當(dāng)前bean。用在方法上,則默認(rèn)依賴類為方法的返回類型
@ConditionalOnClass,指定類在classpath上時(shí),才初始化當(dāng)前bean。用在方法上,則默認(rèn)依賴類為方法的返回類型
@ConditionalOnCloudPlatform,在指定云平臺才注冊配置
@ConditionalOnExpression,指定spel為true時(shí)注冊配置
@ConditionalOnJava,在指定java版本時(shí)注冊配置
@ConditionalOnJndi
@ConditionalOnMissingBean,指定bean不在上下文中時(shí),才初始化當(dāng)前bean。用在方法上,則默認(rèn)依賴類為方法的返回類型
@ConditionalOnMissingClass,指定類不在classpath上時(shí),才初始化當(dāng)前bean。用在方法上,則默認(rèn)依賴類為方法的返回類型
@ConditionalOnNotWebApplication,不是在web環(huán)境才注冊配置
@ConditionalOnProperty,配置文件中的值與指定值是否相等,相等才注冊配置
@ConditionalOnResource,指定resources都在classpath上才注冊配置
@ConditionalOnSingleCandidate,上下文中只有一個(gè)候選者bean時(shí)才注冊配置
@ConditionalOnWebApplication,是在web環(huán)境才注冊配置
五、緩存
@EnableCaching,開啟緩存配置,支持子類代理或者AspectJ增強(qiáng)
@CacheConfig,在一個(gè)類下,提供公共緩存配置
@Cacheable,放著方法和類上,緩存方法或類下所有方法的返回值
@CachePut,每次先執(zhí)行方法,再將結(jié)果放入緩存
@CacheEvict,刪除緩存
@Caching,可以配置@Cacheable、@CachePut、@CacheEvict
六、定時(shí)器
@EnableScheduling,開啟定時(shí)任務(wù)功能
@Scheduled,按指定執(zhí)行周期執(zhí)行方法
@Schedules,包含多個(gè)@Scheduled,可同時(shí)運(yùn)行多個(gè)周期配置
@EnableAsync,開啟方法異步執(zhí)行的能力,通過@Async或者自定義注解找到需要異步執(zhí)行的方法。通過實(shí)現(xiàn)AsyncConfigurer接口的getAsyncExecutor()和getAsyncUncaughtExceptionHandler()方法自定義Executor和異常處理。
@Async,標(biāo)記方法為異步線程中執(zhí)行
七、注入配置文件properties
@EnableConfigurationProperties,啟動(dòng)@ConfigurationProperties功能
@ConfigurationProperties,將properties文件里的內(nèi)容,自動(dòng)注入bean對應(yīng)的屬性中
@DeprecatedConfigurationProperty,用在配置文件的getter()方法上,標(biāo)記字段已經(jīng)過期,并提示替換的字段。一般給spring-boot-configuration-processor使用。
@NestedConfigurationProperty,標(biāo)記在配置文件的字段上,提示spring-boot-configuration-processor,配置包含嵌套的配置。
spring-configuration-metadata.json 提供配置的元信息,在寫properties配置時(shí),會(huì)有語法提示。在項(xiàng)目中引入spring-boot-configuration-processor項(xiàng)目,會(huì)掃描@ConfigurationProperties注解,自動(dòng)生成spring-configuration-metadata.json
八、Jpa
1、@Entity ,@Table(name=“”)
表明這是一個(gè)實(shí)體類,一般用于jpa,這兩個(gè)注解一塊使用,但是如果表名和實(shí)體類名相同的話,@Table可以省略。
2、@MappedSuperClass
基于代碼復(fù)用和模型分離的思想,在項(xiàng)目開發(fā)中使用jpa的@MappedSuperClass注解,將實(shí)體類的多個(gè)屬性分別封裝到不同的非實(shí)體類中。例如,數(shù)據(jù)庫表中都需要id來表示編號,id是這些映射實(shí)體類的通用屬性,交給jpa統(tǒng)一生產(chǎn)主鍵id編號,那么使用一個(gè)父類來封裝這些通用屬性,并用@MappedSuperClass標(biāo)識。
注意:
標(biāo)注為@MappedSuperClass的類將不是一個(gè)完整的實(shí)體類,它將不會(huì)映射到數(shù)據(jù)庫表,但是它的屬性都映射到其子類的數(shù)據(jù)庫字段中。
標(biāo)注@MappedSuperClass的類不能再標(biāo)注@#Entity或@Table注解,也無需實(shí)現(xiàn)序列化接口。
3、@NoRepositoryBean
一般用做父類的repository,有這個(gè)注解,spring不會(huì)去實(shí)例化該repository。
4、@Column
如果字段名和列名相同,則可以省略。
5、@Id
表示該屬性為主鍵。
6、@Transient
表示該屬性并非一個(gè)到數(shù)據(jù)庫表的字段的映射,ORM框架將忽略該屬性。如果一個(gè)屬性并非數(shù)據(jù)庫表的字段映射,就務(wù)必將其標(biāo)注為@Transient,否則,ORM框架默認(rèn)將其注解為@Basic。
7、@Basic
@Basic 是實(shí)體類與數(shù)據(jù)庫字段映射時(shí)最簡單的類型。類型支持Java基本類型(byte、short、int、long、float、double、char、boolean),包裝類,枚舉類,以及實(shí)現(xiàn)了serializable接口的類型。
@basic注解有兩個(gè)屬性:
1.fetch用來指定屬性的加載機(jī)制
有兩個(gè)選項(xiàng):EAGER(即時(shí)加載,默認(rèn)值)和LAZY(懶加載),即時(shí)加載意味著當(dāng)實(shí)例化對象的時(shí)候必須加載該屬性值,懶加載是指當(dāng)實(shí)例化對象時(shí)不加載該對象,只有當(dāng)調(diào)用該屬性時(shí)才加載。
2. optional用來指定屬性是否可空
有兩個(gè)選項(xiàng):true(可空,默認(rèn)值)和false
如果你的實(shí)體類上不加@Basic注解,它也會(huì)自動(dòng)加上@Basic,并使用默認(rèn)值。
8、@JsonIgnore
在實(shí)體類向前臺返回?cái)?shù)據(jù)時(shí)用來忽略不想傳遞給前臺的屬性或接口。
Bean實(shí)體中會(huì)有某些運(yùn)維字段,返回信息給前臺的時(shí)候,不希望將對應(yīng)值一并返回。此時(shí)可以在對應(yīng)屬性上加上@JsonIgnore,或者可以在User類上加上注解@JsonIgnoreProperties(value=“{password}”)
9、@JoinColumn、@OneToOne、@OneToMany、@ManyToOne
九、導(dǎo)入配置文件
1、@PropertySource
引入單個(gè)properties文件:
@PropertySource(value = {"classpath:xxxx/xxxx.properties"})
引入多個(gè)properties文件
@PropertySource(value = {"classpath:xxxx/xxxx.properties","classpath:xxxx/xxxx.properties"})
2、 @ImportResource導(dǎo)入xml配置文件
可以分為兩種模式,相對路徑的classpath,絕對路徑的file。
注意:單文件可以不寫value或locations。
取值:使用@Value注解取配置文件中的值
@Value("${properties中的鍵}")private String xxx;
3、@Import導(dǎo)入額外的配置文件
功能類似XML配置的,用來導(dǎo)入配置類,可以導(dǎo)入帶有@Configuration注解的配置類或?qū)崿F(xiàn)了ImportSelector/ImportBeanDefinitionRegistrar。
@SpringBootApplication
@Import({SmsConfig.class})
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
十、事務(wù)注解
@Transactional
在Spring中,事務(wù)有兩種實(shí)現(xiàn),分別是編程式事務(wù)和聲明式事務(wù)。
編程式事務(wù):
編程式事務(wù)使用TransationTemplate或者直接使用底層的PlatformTransactionManager。對于編程式事務(wù),spring推薦使用TransationTemplate。
聲明式事務(wù):
建立在AOP基礎(chǔ)上,其本質(zhì)是對方法前后進(jìn)行攔截,然后再目標(biāo)方法開始之前創(chuàng)建或者加入一個(gè)事務(wù),在執(zhí)行完目標(biāo)方法之后根據(jù)執(zhí)行情況提交或者回滾事務(wù),通過@Transactional就可以進(jìn)行事務(wù)操作,更快捷而且簡單。推薦使用。
十一、Spring Cloud
1、@EnableEurekaServer
用在springboot啟動(dòng)類上,表示這是一個(gè)eureka服務(wù)注冊中心;
2、@EnableDiscoveryClient
用在springboot啟動(dòng)類上,表示這是一個(gè)服務(wù),可以被注冊中心找到;
3、@LoadBalanced
開啟負(fù)載均衡能力;
4、@EnableCircuitBreaker
用在啟動(dòng)類上,開啟斷路器功能;
5、@HystrixCommand(fallbackMethod=”backMethod”)
用在方法上,fallbackMethod指定斷路回調(diào)方法;
6、@EnableConfigServer
用在啟動(dòng)類上,表示這是一個(gè)配置中心,開啟Config Server;
7、@EnableZuulProxy
開啟zuul路由,用在啟動(dòng)類上;
8、@SpringCloudApplication
@SpringBootApplication
@EnableDiscovertyClient
@EnableCircuitBreaker
分別是SpringBoot注解、注冊服務(wù)中心Eureka注解、斷路器注解。對于SpringCloud來說,這是每一微服務(wù)必須應(yīng)有的三個(gè)注解,所以才推出了@SpringCloudApplication這一注解集合。
9、@ConfigurationProperties
(1)@ConfigurationProperties注解簡介
Spring源碼中大量使用了ConfigurationProperties注解,比如server.port就是由該注解獲取到的,通過與其他注解配合使用,能夠?qū)崿F(xiàn)Bean的按需配置。 該注解有一個(gè)prefix屬性,通過指定的前綴,綁定配置文件中的配置,該注解可以放在類上,也可以放在方法上。
(2)代碼實(shí)例
spring.datasource.url=jdbc:mysql://127.0.0.1:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
@ConfigurationProperties(prefix = "spring.datasource")
@Component
public class DatasourcePro {private String url;private String username;private String password;// 配置文件中是driver-class-name, 轉(zhuǎn)駝峰命名便可以綁定成private String driverClassName;private String type;...
}
以上代碼就實(shí)現(xiàn)了通過配置文件對屬性的賦值。
(3)注意事項(xiàng)
@ConfigurationProperties 和 @value 有著相同的功能,但是 @ConfigurationProperties的寫法更為方便;
@ConfigurationProperties 的 POJO類的命名比較嚴(yán)格,因?yàn)樗仨毢蚿refix的后綴名要一致, 不然值會(huì)綁定不上, 特殊的后綴名是“driver-class-name”這種帶橫杠的情況,在POJO里面的命名規(guī)則是 下劃線轉(zhuǎn)駝峰 就可以綁定成功,所以就是 “driverClassName”。