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

??長按上方微信二維碼 2 秒
感謝點贊支持下哈 
