SpringBoot注解大全
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
作者 | 白色程序猿
來(lái)源 | urlify.cn/bUnQNf
76套java從入門(mén)到精通實(shí)戰(zhàn)課程分享
一、注解(annotations)列表
@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan讓spring Boot掃描到Configuration類(lèi)并把它加入到程序上下文。
@Configuration 等同于spring的XML配置文件;使用Java代碼可以檢查類(lèi)型安全。
@EnableAutoConfiguration 自動(dòng)配置。
@ComponentScan 組件掃描,可自動(dòng)發(fā)現(xiàn)和裝配一些Bean。
@Component可配合CommandLineRunner使用,在程序啟動(dòng)后執(zhí)行一些基礎(chǔ)任務(wù)。
@RestController注解是@Controller和@ResponseBody的合集,表示這是個(gè)控制器bean,并且是將函數(shù)的返回值直 接填入HTTP響應(yīng)體中,是REST風(fēng)格的控制器。
@Autowired自動(dòng)導(dǎo)入。
@PathVariable獲取參數(shù)。
@JsonBackReference解決嵌套外鏈問(wèn)題。
@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。
二、注解(annotations)詳解
@SpringBootApplication:申明讓spring boot自動(dòng)給程序進(jìn)行必要的配置,這個(gè)配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三個(gè)配置。
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@ResponseBody:表示該方法的返回結(jié)果直接寫(xiě)入HTTP response body中,一般在異步獲取數(shù)據(jù)時(shí)使用,用于構(gòu)建RESTful的api。在使用@RequestMapping后,返回值通常解析為跳轉(zhuǎn)路徑,加上@Responsebody后返回結(jié)果不會(huì)被解析為跳轉(zhuǎn)路徑,而是直接寫(xiě)入HTTP response body中。比如異步獲取json數(shù)據(jù),加上@Responsebody后,會(huì)直接返回json數(shù)據(jù)。該注解一般會(huì)配合@RequestMapping一起使用。示例代碼:
1 @RequestMapping(“/test”)
2 @ResponseBody
3 public String test(){
4 return”ok”;
5 }
@Controller:用于定義控制器類(lèi),在spring項(xiàng)目中由控制器負(fù)責(zé)將用戶發(fā)來(lái)的URL請(qǐng)求轉(zhuǎn)發(fā)到對(duì)應(yīng)的服務(wù)接口(service層),一般這個(gè)注解在類(lèi)中,通常方法需要配合注解@RequestMapping。示例代碼:
@Controller
@RequestMapping(“/demoInfo”)
public class DemoController {
@Autowired
private DemoInfoService demoInfoService;
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
System.out.println("DemoController.hello()");
map.put("hello","from TemplateController.helloHtml");
//會(huì)使用hello.html或者h(yuǎn)ello.ftl模板進(jìn)行渲染顯示.
return"/hello";
}
}@RestController:用于標(biāo)注控制層組件(如struts中的action),@ResponseBody和@Controller的合集。示例代碼:
package com.kfit.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/demoInfo2”)
publicclass DemoController2 {
@RequestMapping("/test")
public String test(){
return "ok";
}
}
@RequestMapping:提供路由信息,負(fù)責(zé)URL到Controller中的具體函數(shù)的映射。
@EnableAutoConfiguration:SpringBoot自動(dòng)配置(auto-configuration):嘗試根據(jù)你添加的jar依賴(lài)自動(dòng)配置你的Spring應(yīng)用。例如,如果你的classpath下存在HSQLDB,并且你沒(méi)有手動(dòng)配置任何數(shù)據(jù)庫(kù)連接beans,那么我們將自動(dòng)配置一個(gè)內(nèi)存型(in-memory)數(shù)據(jù)庫(kù)”。你可以將@EnableAutoConfiguration或者@SpringBootApplication注解添加到一個(gè)@Configuration類(lèi)上來(lái)選擇自動(dòng)配置。如果發(fā)現(xiàn)應(yīng)用了你不想要的特定自動(dòng)配置類(lèi),你可以使用@EnableAutoConfiguration注解的排除屬性來(lái)禁用它們。
@ComponentScan:其實(shí)很簡(jiǎn)單,@ComponentScan主要就是定義掃描的路徑從中找出標(biāo)識(shí)了需要裝配的類(lèi)自動(dòng)裝配到spring的bean容器中,你一定都有用過(guò)@Controller,@Service,@Repository注解,查看其源碼你會(huì)發(fā)現(xiàn),他們中有一個(gè)共同的注解@Component,沒(méi)錯(cuò)@ComponentScan注解默認(rèn)就會(huì)裝配標(biāo)識(shí)了@Controller,@Service,@Repository,@Component注解的類(lèi)到spring容器中。當(dāng)然,這個(gè)的前提就是你需要在所掃描包下的類(lèi)上引入注解。
@Configuration:相當(dāng)于傳統(tǒng)的xml配置文件,如果有些第三方庫(kù)需要用到xml文件,建議仍然通過(guò)@Configuration類(lèi)作為項(xiàng)目的配置主類(lèi)——可以使用@ImportResource注解加載xml配置文件。
@Import:用來(lái)導(dǎo)入其他配置類(lèi)。
@ImportResource:用來(lái)加載xml配置文件。
@Autowired:自動(dòng)導(dǎo)入依賴(lài)的bean
@Service:一般用于修飾service層的組件
@Repository:使用@Repository注解可以確保DAO或者repositories提供異常轉(zhuǎn)譯,這個(gè)注解修飾的DAO或者repositories類(lèi)會(huì)被ComponetScan發(fā)現(xiàn)并配置,同時(shí)也不需要為它們提供XML配置項(xiàng)。
@Bean:用@Bean標(biāo)注方法等價(jià)于XML中配置的bean。
@Value:注入Spring boot application.properties配置的屬性的值。示例代碼:
1 @Value(value = “#{message}”)
2 private String message;
@Inject:等價(jià)于默認(rèn)的@Autowired,只是沒(méi)有required屬性;
@Component:泛指組件,當(dāng)組件不好歸類(lèi)的時(shí)候,我們可以使用這個(gè)注解進(jìn)行標(biāo)注。
@Bean:相當(dāng)于XML中的,放在方法的上面,而不是類(lèi),意思是產(chǎn)生一個(gè)bean,并交給spring管理。
@AutoWired:自動(dòng)導(dǎo)入依賴(lài)的bean。byType方式。把配置好的Bean拿來(lái)用,完成屬性、方法的組裝,它可以對(duì)類(lèi)成員變量、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作。當(dāng)加上(required=false)時(shí),就算找不到bean也不報(bào)錯(cuò)。
@Qualifier:當(dāng)有多個(gè)同一類(lèi)型的Bean時(shí),可以用@Qualifier(“name”)來(lái)指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據(jù)名字進(jìn)行注入,但能進(jìn)行更細(xì)粒度的控制如何選擇候選者,具體使用方式如下:
1 @Autowired
2 @Qualifier(value = “demoInfoService”)
3 private DemoInfoService demoInfoService;
@Resource(name=”name”,type=”type”):沒(méi)有括號(hào)內(nèi)內(nèi)容的話,默認(rèn)byName。與@Autowired干類(lèi)似的事。
三、JPA注解
@Entity:@Table(name=”“):表明這是一個(gè)實(shí)體類(lèi)。一般用于jpa這兩個(gè)注解一般一塊使用,但是如果表名和實(shí)體類(lèi)名相同的話,@Table可以省略
@MappedSuperClass:用在確定是父類(lèi)的entity上。父類(lèi)的屬性子類(lèi)可以繼承。
@NoRepositoryBean:一般用作父類(lèi)的repository,有這個(gè)注解,spring不會(huì)去實(shí)例化該repository。
@Column:如果字段名與列名相同,則可以省略。
@Id:表示該屬性為主鍵。
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主鍵生成策略是sequence(可以為Auto、IDENTITY、native等,Auto表示可在多個(gè)數(shù)據(jù)庫(kù)間切換),指定sequence的名字是repair_seq。
@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name為sequence的名稱(chēng),以便使用,sequenceName為數(shù)據(jù)庫(kù)的sequence名稱(chēng),兩個(gè)名稱(chēng)可以一致。
@Transient:表示該屬性并非一個(gè)到數(shù)據(jù)庫(kù)表的字段的映射,ORM框架將忽略該屬性。如果一個(gè)屬性并非數(shù)據(jù)庫(kù)表的字段映射,就務(wù)必將其標(biāo)示為@Transient,否則,ORM框架默認(rèn)其注解為@Basic。@Basic(fetch=FetchType.LAZY):標(biāo)記可以指定實(shí)體屬性的加載方式
@JsonIgnore:作用是json序列化時(shí)將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
@JoinColumn(name=”loginId”):一對(duì)一:本表中指向另一個(gè)表的外鍵。一對(duì)多:另一個(gè)表指向本表的外鍵。
@OneToOne、@OneToMany、@ManyToOne:對(duì)應(yīng)hibernate配置文件中的一對(duì)一,一對(duì)多,多對(duì)一。
四、springMVC相關(guān)注解
@RequestMapping:@RequestMapping(“/path”)表示該控制器處理所有“/path”的UR L請(qǐng)求。RequestMapping是一個(gè)用來(lái)處理請(qǐng)求地址映射的注解,可用于類(lèi)或方法上。
用于類(lèi)上,表示類(lèi)中的所有響應(yīng)請(qǐng)求的方法都是以該地址作為父路徑。該注解有六個(gè)屬性:
params:指定request中必須包含某些參數(shù)值是,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請(qǐng)求。
value:指定請(qǐng)求的實(shí)際地址,指定的地址可以是URI Template 模式
method:指定請(qǐng)求的method類(lèi)型, GET、POST、PUT、DELETE等
consumes:指定處理請(qǐng)求的提交內(nèi)容類(lèi)型(Content-Type),如application/json,text/html;
produces:指定返回的內(nèi)容類(lèi)型,僅當(dāng)request請(qǐng)求頭中的(Accept)類(lèi)型中包含該指定類(lèi)型才返回
@RequestParam:用在方法的參數(shù)前面。
@RequestParam
String a =request.getParameter(“a”)。
@PathVariable:路徑變量。如
1 RequestMapping(“user/get/mac/{macAddress}”)
2 public String getByMacAddress(@PathVariable String macAddress){
3 //do something;
4 }參數(shù)與大括號(hào)里的名字一樣要相同。
五、全局異常處理
@ControllerAdvice:包含@Component。可以被掃描到。統(tǒng)一處理異常。
@ExceptionHandler(Exception.class):用在方法上面表示遇到這個(gè)異常就執(zhí)行以下方法。
六、項(xiàng)目中具體配置解析和使用環(huán)境
@MappedSuperclass:
1.@MappedSuperclass 注解使用在父類(lèi)上面,是用來(lái)標(biāo)識(shí)父類(lèi)的
2.@MappedSuperclass 標(biāo)識(shí)的類(lèi)表示其不能映射到數(shù)據(jù)庫(kù)表,因?yàn)槠洳皇且粋€(gè)完整的實(shí)體類(lèi),但是它所擁有的屬性能夠映射在其子類(lèi)對(duì)用的數(shù)據(jù)庫(kù)表中
3.@MappedSuperclass 標(biāo)識(shí)的類(lèi)不能再有@Entity或@Table注解
@Column:
1.當(dāng)實(shí)體的屬性與其映射的數(shù)據(jù)庫(kù)表的列不同名時(shí)需要使用@Column標(biāo)注說(shuō)明,該屬性通常置于實(shí)體的屬性聲明語(yǔ)句之前,還可與 @Id 標(biāo)注一起使用。
2.@Column 標(biāo)注的常用屬性是name,用于設(shè)置映射數(shù)據(jù)庫(kù)表的列名。此外,該標(biāo)注還包含其它多個(gè)屬性,如:unique、nullable、length、precision等。具體如下:
1 name屬性:name屬性定義了被標(biāo)注字段在數(shù)據(jù)庫(kù)表中所對(duì)應(yīng)字段的名稱(chēng)
2 unique屬性:unique屬性表示該字段是否為唯一標(biāo)識(shí),默認(rèn)為false,如果表中有一個(gè)字段需要唯一標(biāo)識(shí),則既可以使用該標(biāo)記,也可以使用@Table注解中的@UniqueConstraint
3 nullable屬性:nullable屬性表示該字段是否可以為null值,默認(rèn)為true
4 insertable屬性:insertable屬性表示在使用”INSERT”語(yǔ)句插入數(shù)據(jù)時(shí),是否需要插入該字段的值
5 updateable屬性:updateable屬性表示在使用”UPDATE”語(yǔ)句插入數(shù)據(jù)時(shí),是否需要更新該字段的值
6 insertable和updateable屬性:一般多用于只讀的屬性,例如主鍵和外鍵等,這些字段通常是自動(dòng)生成的
7 columnDefinition屬性:columnDefinition屬性表示創(chuàng)建表時(shí),該字段創(chuàng)建的SQL語(yǔ)句,一般用于通過(guò)Entity生成表定義時(shí)使用,如果數(shù)據(jù)庫(kù)中表已經(jīng)建好,該屬性沒(méi)有必要使用
8 table屬性:table屬性定義了包含當(dāng)前字段的表名
9 length屬性:length屬性表示字段的長(zhǎng)度,當(dāng)字段的類(lèi)型為varchar時(shí),該屬性才有效,默認(rèn)為255個(gè)字符
10 precision屬性和scale屬性:precision屬性和scale屬性一起表示精度,當(dāng)字段類(lèi)型為double時(shí),precision表示數(shù)值的總長(zhǎng)度,scale表示小數(shù)點(diǎn)所占的位數(shù)
具體如下: 1.double類(lèi)型將在數(shù)據(jù)庫(kù)中映射為double類(lèi)型,precision和scale屬性無(wú)效 2.double類(lèi)型若在columnDefinition屬性中指定數(shù)字類(lèi)型為decimal并指定精度,則最終以columnDefinition為準(zhǔn) 3.BigDecimal類(lèi)型在數(shù)據(jù)庫(kù)中映射為decimal類(lèi)型,precision和scale屬性有效 4.precision和scale屬性只在BigDecimal類(lèi)型中有效
3.@Column 標(biāo)注的columnDefinition屬性: 表示該字段在數(shù)據(jù)庫(kù)中的實(shí)際類(lèi)型.通常 ORM 框架可以根據(jù)屬性類(lèi)型自動(dòng)判斷數(shù)據(jù)庫(kù)中字段的類(lèi)型,但是對(duì)于Date類(lèi)型仍無(wú)法確定數(shù)據(jù)庫(kù)中字段類(lèi)型究竟是DATE,TIME還是TIMESTAMP.此外,String的默認(rèn)映射類(lèi)型為VARCHAR,如果要將 String 類(lèi)型映射到特定數(shù)據(jù)庫(kù)的 BLOB 或TEXT字段類(lèi)型.
4.@Column標(biāo)注也可置于屬性的getter方法之前
@Getter和@Setter(Lombok)
@Setter:注解在屬性上;為屬性提供 setting 方法 @Getter:注解在屬性上;為屬性提供 getting 方法擴(kuò)展: @Data:注解在類(lèi)上;提供類(lèi)所有屬性的 getting 和 setting 方法,此外還提供了equals、canEqual、hashCode、toString 方法
@Setter:注解在屬性上;為屬性提供 setting 方法
@Getter:注解在屬性上;為屬性提供 getting 方法
@Log4j2 :注解在類(lèi)上;為類(lèi)提供一個(gè) 屬性名為log 的 log4j 日志對(duì)象,和@Log4j注解類(lèi)似
@NoArgsConstructor:注解在類(lèi)上;為類(lèi)提供一個(gè)無(wú)參的構(gòu)造方法
@AllArgsConstructor:注解在類(lèi)上;為類(lèi)提供一個(gè)全參的構(gòu)造方法
@EqualsAndHashCode:默認(rèn)情況下,會(huì)使用所有非瞬態(tài)(non-transient)和非靜態(tài)(non-static)字段來(lái)生成equals和hascode方法,也可以指定具體使用哪些屬性。
@toString:生成toString方法,默認(rèn)情況下,會(huì)輸出類(lèi)名、所有屬性,屬性會(huì)按照順序輸出,以逗號(hào)分割。
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
無(wú)參構(gòu)造器、部分參數(shù)構(gòu)造器、全參構(gòu)造器,當(dāng)我們需要重載多個(gè)構(gòu)造器的時(shí)候,只能自己手寫(xiě)了
@NonNull:注解在屬性上,如果注解了,就必須不能為Null
@val:注解在屬性上,如果注解了,就是設(shè)置為final類(lèi)型,可查看源碼的注釋知道
@PreUpdate和@PrePersist
@PreUpdate1.用于為相應(yīng)的生命周期事件指定回調(diào)方法。2.該注釋可以應(yīng)用于實(shí)體類(lèi),映射超類(lèi)或回調(diào)監(jiān)聽(tīng)器類(lèi)的方法。3.用于setter 如果要每次更新實(shí)體時(shí)更新實(shí)體的屬性,可以使用@PreUpdate注釋。4.使用該注釋?zhuān)槐卦诿看胃掠脩魧?shí)體時(shí)顯式更新相應(yīng)的屬性。5.preUpdate不允許您更改您的實(shí)體。您只能使用傳遞給事件的計(jì)算的更改集來(lái)修改原始字段值。@Prepersist1.查看@PrePersist注釋?zhuān)瑤椭诔志没白詣?dòng)填充實(shí)體屬性。2.可以用來(lái)在使用jpa的時(shí)記錄一些業(yè)務(wù)無(wú)關(guān)的字段,比如最后更新時(shí)間等等。生命周期方法注解(delete沒(méi)有生命周期事件)3.@PrePersist save之前被調(diào)用,它可以返回一個(gè)DBObject代替一個(gè)空的 @PostPersist save到datastore之后被調(diào)用4.@PostLoad 在Entity被映射之后被調(diào)用 @EntityListeners 指定外部生命周期事件實(shí)現(xiàn)類(lèi)實(shí)體Bean生命周期的回調(diào)事件
方法的標(biāo)注: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad 。
它們標(biāo)注在某個(gè)方法之前,沒(méi)有任何參數(shù)。這些標(biāo)注下的方法在實(shí)體的狀態(tài)改變前后時(shí)進(jìn)行調(diào)用,相當(dāng)于攔截器;
pre 表示在狀態(tài)切換前觸發(fā),post 則表示在切換后觸發(fā)。
@PostLoad 事件在下列情況觸發(fā):
1. 執(zhí)行 EntityManager.find()或 getreference()方法載入一個(gè)實(shí)體后;
2. 執(zhí)行 JPA QL 查詢過(guò)后;
3. EntityManager.refresh( )方法被調(diào)用后。
@PrePersist 和 @PostPersist事件在實(shí)體對(duì)象插入到數(shù)據(jù)庫(kù)的過(guò)程中發(fā)生;
@PrePersist 事件在調(diào)用 EntityManager.persist()方法后立刻發(fā)生,級(jí)聯(lián)保存也會(huì)發(fā)生此事件,此時(shí)的數(shù)據(jù)還沒(méi)有真實(shí)插入進(jìn)數(shù)據(jù)庫(kù)。
@PostPersist 事件在數(shù)據(jù)已經(jīng)插入進(jìn)數(shù)據(jù)庫(kù)后發(fā)生。
@PreUpdate 和 @PostUpdate 事件的觸發(fā)由更新實(shí)體引起, @PreUpdate 事件在實(shí)體的狀態(tài)同步到數(shù)據(jù)庫(kù)之前觸發(fā),此時(shí)的數(shù)據(jù)還沒(méi)有真實(shí)更新到數(shù)據(jù)庫(kù)。
@PostUpdate 事件在實(shí)體的狀態(tài)同步到數(shù)據(jù)庫(kù)后觸發(fā),同步在事務(wù)提交時(shí)發(fā)生。
@PreRemove 和 @PostRemove 事件的觸發(fā)由刪除實(shí)體引起,@ PreRemove 事件在實(shí)體從數(shù)據(jù)庫(kù)刪除之前觸發(fā),即調(diào)用了 EntityManager.remove()方法或者級(jí)聯(lián)刪除
當(dāng)你在執(zhí)行各種持久化方法的時(shí)候,實(shí)體的狀態(tài)會(huì)隨之改變,狀態(tài)的改變會(huì)引發(fā)不同的生命周期事件。這些事件可以使用不同的注釋符來(lái)指示發(fā)生時(shí)的回調(diào)函數(shù)。
@javax.persistence.PostLoad:加載后。
@javax.persistence.PrePersist:持久化前。
@javax.persistence.PostPersist:持久化后。
@javax.persistence.PreUpdate:更新前。
@javax.persistence.PostUpdate:更新后。
@javax.persistence.PreRemove:刪除前。
@javax.persistence.PostRemove:刪除后。

1)數(shù)據(jù)庫(kù)查詢
@PostLoad事件在下列情況下觸發(fā):
執(zhí)行EntityManager.find()或getreference()方法載入一個(gè)實(shí)體后。
執(zhí)行JPQL查詢后。
EntityManager.refresh()方法被調(diào)用后。
2)數(shù)據(jù)庫(kù)插入
@PrePersist和@PostPersist事件在實(shí)體對(duì)象插入到數(shù)據(jù)庫(kù)的過(guò)程中發(fā)生:
@PrePersist事件在調(diào)用persist()方法后立刻發(fā)生,此時(shí)的數(shù)據(jù)還沒(méi)有真正插入進(jìn)數(shù)據(jù)庫(kù)。
@PostPersist事件在數(shù)據(jù)已經(jīng)插入進(jìn)數(shù)據(jù)庫(kù)后發(fā)生。
3)數(shù)據(jù)庫(kù)更新
@PreUpdate和@PostUpdate事件的觸發(fā)由更新實(shí)體引起:
@PreUpdate事件在實(shí)體的狀態(tài)同步到數(shù)據(jù)庫(kù)之前觸發(fā),此時(shí)的數(shù)據(jù)還沒(méi)有真正更新到數(shù)據(jù)庫(kù)。
@PostUpdate事件在實(shí)體的狀態(tài)同步到數(shù)據(jù)庫(kù)之后觸發(fā),同步在事務(wù)提交時(shí)發(fā)生。
4)數(shù)據(jù)庫(kù)刪除
@PreRemove和@PostRemove事件的觸發(fā)由刪除實(shí)體引起:
@PreRemove事件在實(shí)體從數(shù)據(jù)庫(kù)刪除之前觸發(fā),即在調(diào)用remove()方法刪除時(shí)發(fā)生,此時(shí)的數(shù)據(jù)還沒(méi)有真正從數(shù)據(jù)庫(kù)中刪除。
@PostRemove事件在實(shí)體從數(shù)據(jù)庫(kù)中刪除后觸發(fā)。
@NoArgsConstructor & @AllArgsConstructor(lombok)
@NoArgsConstructor,提供一個(gè)無(wú)參的構(gòu)造方法。
@AllArgsConstructor,提供一個(gè)全參的構(gòu)造方法。
@Configuration & @bean1.@Configuration標(biāo)注在類(lèi)上,相當(dāng)于把該類(lèi)作為spring的xml配置文件中的<beans>,作用為:配置spring容器(應(yīng)用上下文)
package com.test.spring.support.configuration;
@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器啟動(dòng)初始化。。。");
}
}
相當(dāng)于: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>
主方法進(jìn)行測(cè)試: package com.test.spring.support.configuration;
public class TestMain {
public static void main(String[] args) {
//@Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//如果加載spring-context.xml文件:
//ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
}
}
從運(yùn)行主方法結(jié)果可以看出,spring容器已經(jīng)啟動(dòng)了:
1 八月 11, 2016 12:04:11 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2 信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@203e25d3: startup date [Thu Aug 11 12:04:11 CST 2016]; root of context hierarchy
3 spring容器啟動(dòng)初始化。。。2.@Bean標(biāo)注在方法上(返回某個(gè)實(shí)例的方法),等價(jià)于spring的xml配置文件中的<bean>,作用為:注冊(cè)bean對(duì)象
bean類(lèi):
package com.test.spring.support.configuration;
public class TestBean {
public void sayHello(){
System.out.println("TestBean sayHello...");
}
public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
public void start(){
System.out.println("TestBean 初始化。。。");
}
public void cleanUp(){
System.out.println("TestBean 銷(xiāo)毀。。。");
}
}
配置類(lèi):
package com.test.spring.support.configuration;
@Configuration
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器啟動(dòng)初始化。。。");
}
//@Bean注解注冊(cè)bean,同時(shí)可以指定初始化和銷(xiāo)毀方法
//@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}
主方法測(cè)試類(lèi):
package com.test.spring.support.configuration;
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//獲取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}
注:
(1)、@Bean注解在返回實(shí)例的方法上,如果未通過(guò)@Bean指定bean的名稱(chēng),則默認(rèn)與標(biāo)注的方法名相同;
(2)、@Bean注解默認(rèn)作用域?yàn)閱卫齭ingleton作用域,可通過(guò)@Scope(“prototype”)設(shè)置為原型作用域;
(3)、既然@Bean的作用是注冊(cè)bean對(duì)象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注冊(cè)bean,當(dāng)然需要配置@ComponentScan注解進(jìn)行自動(dòng)掃描。
bean類(lèi):
package com.test.spring.support.configuration;
//添加注冊(cè)bean的注解
@Component
public class TestBean {
public void sayHello(){
System.out.println("TestBean sayHello...");
}
public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
}
配置類(lèi):
1
//開(kāi)啟注解配置
2 @Configuration
3 //添加自動(dòng)掃描注解,basePackages為T(mén)estBean包路徑
4 @ComponentScan(basePackages = "com.test.spring.support.configuration")
5 public class TestConfiguration {
6 public TestConfiguration(){
7 System.out.println("spring容器啟動(dòng)初始化。。。");
8 }
9
10 //取消@Bean注解注冊(cè)bean的方式
11 //@Bean
12 //@Scope("prototype")
13 //public TestBean testBean() {
14 // return new TestBean();
15 //}
16 }
主方法測(cè)試獲取bean對(duì)象:
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//獲取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}
sayHello()方法都被正常調(diào)用。
使用@Configuration注解來(lái)代替Spring的bean配置
下面是一個(gè)典型的Spring配置文件(application-config.xml):
<beans>
<bean id="orderService" class="com.acme.OrderService"/>
<constructor-arg ref="orderRepository"/>
</bean>
<bean id="orderRepository" class="com.acme.OrderRepository"/>
<constructor-arg ref="dataSource"/>
</bean>
</beans>
然后你就可以像這樣來(lái)使用是bean了:
1 ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
2 OrderService orderService = (OrderService) ctx.getBean("orderService");
現(xiàn)在Spring Java Configuration這個(gè)項(xiàng)目提供了一種通過(guò)java代碼來(lái)裝配bean的方案:
@Configuration
public class ApplicationConfig {
public @Bean OrderService orderService() {
return new OrderService(orderRepository());
}
public @Bean OrderRepository orderRepository() {
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource() {
// instantiate and return an new DataSource …
}
}
然后你就可以像這樣來(lái)使用是bean了:
1 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
2 OrderService orderService = ctx.getBean(OrderService.class);這么做有什么好處呢?
1.使用純java代碼,不在需要xml
2.在配置中也可享受OO帶來(lái)的好處(面向?qū)ο?
3.類(lèi)型安全對(duì)重構(gòu)也能提供良好的支持
4.減少?gòu)?fù)雜配置文件的同時(shí)依舊能享受到所有springIoC容器提供的功能
粉絲福利:Java從入門(mén)到入土學(xué)習(xí)路線圖
??????

??長(zhǎng)按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
