SpringBoot註解大全

1、註解(annotations)列表html

@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration註解。其中@ComponentScan讓spring Boot掃描到Configuration類並把它加入到程序上下文。java

@Configuration 等同於spring的XML配置文件;使用Java代碼能夠檢查類型安全。web

@EnableAutoConfiguration 自動配置。spring

@ComponentScan 組件掃描,可自動發現和裝配一些Bean。數據庫

@Component可配合CommandLineRunner使用,在程序啓動後執行一些基礎任務。json

@RestController註解是@Controller和@ResponseBody的合集,表示這是個控制器bean,而且是將函數的返回值直 接填入HTTP響應體中,是REST風格的控制器。api

@Autowired自動導入。安全

@PathVariable獲取參數。app

@JsonBackReference解決嵌套外鏈問題。框架

@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。

2、註解(annotations)詳解

@SpringBootApplication:申明讓spring boot自動給程序進行必要的配置,這個配置等同於:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三個配置。

複製代碼
  1 package com.example.myproject;
  2 import org.springframework.boot.SpringApplication;
  3 import org.springframework.boot.autoconfigure.SpringBootApplication;
  4 
  5 @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan 
  6 public class Application {
  7    public static void main(String[] args) {
  8      SpringApplication.run(Application.class, args);
  9    }
 10 }
複製代碼

@ResponseBody:表示該方法的返回結果直接寫入HTTP response body中,通常在異步獲取數據時使用,用於構建RESTful的api。在使用@RequestMapping後,返回值一般解析爲跳轉路徑,加上@esponsebody後返回結果不會被解析爲跳轉路徑,而是直接寫入HTTP response body中。好比異步獲取json數據,加上@Responsebody後,會直接返回json數據。該註解通常會配合@RequestMapping一塊兒使用。示例代碼:

  1 @RequestMapping(「/test」)
  2 @ResponseBody
  3 public String test(){
  4    return」ok」;
  5 }

@Controller:用於定義控制器類,在spring項目中由控制器負責將用戶發來的URL請求轉發到對應的服務接口(service層),通常這個註解在類中,一般方法須要配合註解@RequestMapping。示例代碼:

複製代碼
  1 @Controller
  2 @RequestMapping(「/demoInfo」)
  3 public class DemoController {
  4 @Autowired
  5 private DemoInfoService demoInfoService;
  6 
  7 @RequestMapping("/hello")
  8 public String hello(Map<String,Object> map){
  9    System.out.println("DemoController.hello()");
 10    map.put("hello","from TemplateController.helloHtml");
 11    //會使用hello.html或者hello.ftl模板進行渲染顯示.
 12    return"/hello";
 13 }
 14 }
複製代碼

@RestController:用於標註控制層組件(如struts中的action),@ResponseBody和@Controller的合集。示例代碼:

複製代碼
  1 package com.kfit.demo.web;
  2 
  3 import org.springframework.web.bind.annotation.RequestMapping;
  4 import org.springframework.web.bind.annotation.RestController;
  5 
  6 
  7 @RestController
  8 @RequestMapping(「/demoInfo2」)
  9 publicclass DemoController2 {
 10 
 11 @RequestMapping("/test")
 12 public String test(){
 13    return "ok";
 14 }
 15 }
複製代碼

@RequestMapping:提供路由信息,負責URL到Controller中的具體函數的映射。

@EnableAutoConfiguration:SpringBoot自動配置(auto-configuration):嘗試根據你添加的jar依賴自動配置你的Spring應用。例如,若是你的classpath下存在HSQLDB,而且你沒有手動配置任何數據庫鏈接beans,那麼咱們將自動配置一個內存型(in-memory)數據庫」。你能夠將@EnableAutoConfiguration或者@SpringBootApplication註解添加到一個@Configuration類上來選擇自動配置。若是發現應用了你不想要的特定自動配置類,你可使用@EnableAutoConfiguration註解的排除屬性來禁用它們。

@ComponentScan:其實很簡單,@ComponentScan主要就是定義掃描的路徑從中找出標識了須要裝配的類自動裝配到spring的bean容器中,你必定都有用過@Controller,@Service,@Repository註解,查看其源碼你會發現,他們中有一個共同的註解@Component,沒錯@ComponentScan註解默認就會裝配標識了@Controller,@Service,@Repository,@Component註解的類到spring容器中。固然,這個的前提就是你須要在所掃描包下的類上引入註解。

@Configuration:至關於傳統的xml配置文件,若是有些第三方庫須要用到xml文件,建議仍然經過@Configuration類做爲項目的配置主類——可使用@ImportResource註解加載xml配置文件。

@Import:用來導入其餘配置類。

@ImportResource:用來加載xml配置文件。

@Autowired:自動導入依賴的bean

@Service:通常用於修飾service層的組件

@Repository:使用@Repository註解能夠確保DAO或者repositories提供異常轉譯,這個註解修飾的DAO或者repositories類會被ComponetScan發現並配置,同時也不須要爲它們提供XML配置項。

@Bean:用@Bean標註方法等價於XML中配置的bean。

@Value:注入Spring boot application.properties配置的屬性的值。示例代碼:

  1 @Value(value = 「#{message}」)
  2 private String message;

@Inject:等價於默認的@Autowired,只是沒有required屬性;

@Component:泛指組件,當組件很差歸類的時候,咱們可使用這個註解進行標註。

@Bean:至關於XML中的,放在方法的上面,而不是類,意思是產生一個bean,並交給spring管理。

@AutoWired:自動導入依賴的bean。byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它能夠對類成員變量、方法及構造函數進行標註,完成自動裝配的工做。當加上(required=false)時,就算找不到bean也不報錯。

@Qualifier:當有多個同一類型的Bean時,能夠用@Qualifier(「name」)來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據名字進行注入,但能進行更細粒度的控制如何選擇候選者,具體使用方式以下:

  1 @Autowired
  2 @Qualifier(value = 「demoInfoService」)
  3 private DemoInfoService demoInfoService;

@Resource(name=」name」,type=」type」):沒有括號內內容的話,默認byName。與@Autowired幹相似的事。

3、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表示可在多個數據庫間切換),指定sequence的名字是repair_seq。

@SequenceGeneretor(name = 「repair_seq」, sequenceName = 「seq_repair」, allocationSize = 1):name爲sequence的名稱,以便使用,sequenceName爲數據庫的sequence名稱,兩個名稱能夠一致。

@Transient:表示該屬性並不是一個到數據庫表的字段的映射,ORM框架將忽略該屬性。若是一個屬性並不是數據庫表的字段映射,就務必將其標示爲@Transient,不然,ORM框架默認其註解爲@Basic。@Basic(fetch=FetchType.LAZY):標記能夠指定實體屬性的加載方式

@JsonIgnore:做用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。

@JoinColumn(name=」loginId」):一對一:本表中指向另外一個表的外鍵。一對多:另外一個表指向本表的外鍵。

@OneToOne、@OneToMany、@ManyToOne:對應hibernate配置文件中的一對一,一對多,多對一。

4、springMVC相關注解

@RequestMapping:@RequestMapping(「/path」)表示該控制器處理全部「/path」的UR L請求。RequestMapping是一個用來處理請求地址映射的註解,可用於類或方法上。
用於類上,表示類中的全部響應請求的方法都是以該地址做爲父路徑。該註解有六個屬性:
params:指定request中必須包含某些參數值是,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。
value:指定請求的實際地址,指定的地址能夠是URI Template 模式
method:指定請求的method類型, GET、POST、PUT、DELETE等
consumes:指定處理請求的提交內容類型(Content-Type),如application/json,text/html;
produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回

@RequestParam:用在方法的參數前面。
@RequestParam
String a =request.getParameter(「a」)。

@PathVariable:路徑變量。如

  1 RequestMapping(「user/get/mac/{macAddress}」)
  2 public String getByMacAddress(@PathVariable String macAddress){
  3    //do something; 
  4 }

參數與大括號裏的名字同樣要相同。

5、全局異常處理

@ControllerAdvice:包含@Component。能夠被掃描到。統一處理異常。

@ExceptionHandler(Exception.class):用在方法上面表示遇到這個異常就執行如下方法。


6、項目中具體配置解析和使用環境

@MappedSuperclass:

1.@MappedSuperclass 註解使用在父類上面,是用來標識父類的

2.@MappedSuperclass 標識的類表示其不能映射到數據庫表,由於其不是一個完整的實體類,可是它所擁有的屬性可以映射在其子類對用的數據庫表中

3.@MappedSuperclass 標識的類不能再有@Entity或@Table註解

@Column:

1.當實體的屬性與其映射的數據庫表的列不一樣名時須要使用@Column標註說明,該屬性一般置於實體的屬性聲明語句以前,還可與 @Id 標註一塊兒使用。

2.@Column 標註的經常使用屬性是name,用於設置映射數據庫表的列名。此外,該標註還包含其它多個屬性,如:unique、nullable、length、precision等。具體以下:

複製代碼
  1 name屬性:name屬性定義了被標註字段在數據庫表中所對應字段的名稱
  2 unique屬性:unique屬性表示該字段是否爲惟一標識,默認爲false,若是表中有一個字段須要惟一標識,則既可使用該標記,也可使用@Table註解中的@UniqueConstraint
  3 nullable屬性:nullable屬性表示該字段是否能夠爲null值,默認爲true
  4 insertable屬性:insertable屬性表示在使用」INSERT」語句插入數據時,是否須要插入該字段的值
  5 updateable屬性:updateable屬性表示在使用」UPDATE」語句插入數據時,是否須要更新該字段的值
  6 insertable和updateable屬性:通常多用於只讀的屬性,例如主鍵和外鍵等,這些字段一般是自動生成的
  7 columnDefinition屬性:columnDefinition屬性表示建立表時,該字段建立的SQL語句,通常用於經過Entity生成表定義時使用,若是數據庫中表已經建好,該屬性沒有必要使用
  8 table屬性:table屬性定義了包含當前字段的表名
  9 length屬性:length屬性表示字段的長度,當字段的類型爲varchar時,該屬性纔有效,默認爲255個字符
 10 precision屬性和scale屬性:precision屬性和scale屬性一塊兒表示精度,當字段類型爲double時,precision表示數值的總長度,scale表示小數點所佔的位數
    具體以下:
1.double類型將在數據庫中映射爲double類型,precision和scale屬性無效
2.double類型若在columnDefinition屬性中指定數字類型爲decimal並指定精度,則最終以columnDefinition爲準
3.BigDecimal類型在數據庫中映射爲decimal類型,precision和scale屬性有效
4.precision和scale屬性只在BigDecimal類型中有效
複製代碼

3.@Column 標註的columnDefinition屬性: 表示該字段在數據庫中的實際類型.一般 ORM 框架能夠根據屬性類型自動判斷數據庫中字段的類型,可是對於Date類型仍沒法肯定數據庫中字段類型到底是DATE,TIME仍是TIMESTAMP.此外,String的默認映射類型爲VARCHAR,若是要將 String 類型映射到特定數據庫的 BLOB 或TEXT字段類型.

4.@Column標註也可置於屬性的getter方法以前

@Getter和@Setter(Lombok)

@Setter:註解在屬性上;爲屬性提供 setting 方法 @Getter:註解在屬性上;爲屬性提供 getting 方法
擴展:
複製代碼
  1 @Data:註解在類上;提供類全部屬性的 getting 和 setting 方法,此外還提供了equals、canEqual、hashCode、toString 方法
  2 
  3 @Setter:註解在屬性上;爲屬性提供 setting 方法
  4 
  5 @Getter:註解在屬性上;爲屬性提供 getting 方法
  6 
  7 @Log4j2 :註解在類上;爲類提供一個 屬性名爲log 的 log4j 日誌對象,和@Log4j註解相似
  8 
  9 @NoArgsConstructor:註解在類上;爲類提供一個無參的構造方法
 10 
 11 @AllArgsConstructor:註解在類上;爲類提供一個全參的構造方法
 12 
 13 @EqualsAndHashCode:默認狀況下,會使用全部非瞬態(non-transient)和非靜態(non-static)字段來生成equals和hascode方法,也能夠指定具體使用哪些屬性。
 14 
 15 @toString:生成toString方法,默認狀況下,會輸出類名、全部屬性,屬性會按照順序輸出,以逗號分割。
 16 
 17 @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
 18 無參構造器、部分參數構造器、全參構造器,當咱們須要重載多個構造器的時候,只能本身手寫了
 19 
 20 @NonNull:註解在屬性上,若是註解了,就必須不能爲Null
 21 
 22 @val:註解在屬性上,若是註解了,就是設置爲final類型,可查看源碼的註釋知道
複製代碼

@PreUpdate和@PrePersist

@PreUpdate
1.用於爲相應的生命週期事件指定回調方法。
2.該註釋能夠應用於實體類,映射超類或回調監聽器類的方法。
3.用於setter 若是要每次更新實體時更新實體的屬性,可使用@PreUpdate註釋。
4.使用該註釋,您沒必要在每次更新用戶實體時顯式更新相應的屬性。
5.preUpdate不容許您更改您的實體。 您只能使用傳遞給事件的計算的更改集來修改原始字段值。
 
@Prepersist
1.查看@PrePersist註釋,幫助您在持久化以前自動填充實體屬性。
2.能夠用來在使用jpa的時記錄一些業務無關的字段,好比最後更新時間等等。生命週期方法註解(delete沒有生命週期事件)
3.@PrePersist save以前被調用,它能夠返回一個DBObject代替一個空的 @PostPersist save到datastore以後被調用 
4.@PostLoad 在Entity被映射以後被調用 @EntityListeners 指定外部生命週期事件實現類 

實體Bean生命週期的回調事件

複製代碼
方法的標註: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad 。
它們標註在某個方法以前,沒有任何參數。這些標註下的方法在實體的狀態改變先後時進行調用,至關於攔截器;
pre 表示在狀態切換前觸發,post 則表示在切換後觸發。 
@PostLoad 事件在下列狀況觸發: 
1. 執行 EntityManager.find()或 getreference()方法載入一個實體後; 
2. 執行 JPA QL 查詢事後; 
3. EntityManager.refresh( )方法被調用後。 
@PrePersist 和 @PostPersist事件在實體對象插入到數據庫的過程當中發生;
@PrePersist 事件在調用 EntityManager.persist()方法後馬上發生,級聯保存也會發生此事件,此時的數據尚未真實插入進數據庫。
@PostPersist 事件在數據已經插入進數據庫後發生。
@PreUpdate 和 @PostUpdate 事件的觸發由更新實體引發, @PreUpdate 事件在實體的狀態同步到數據庫以前觸發,此時的數據尚未真實更新到數據庫。
@PostUpdate 事件在實體的狀態同步到數據庫後觸發,同步在事務提交時發生。 
@PreRemove 和 @PostRemove 事件的觸發由刪除實體引發,@ PreRemove 事件在實體從數據庫刪除以前觸發,即調用了 EntityManager.remove()方法或者級聯刪除
 
 

當你在執行各類持久化方法的時候,實體的狀態會隨之改變,狀態的改變會引起不一樣的生命週期事件。這些事件可使用不一樣的註釋符來指示發生時的回調函數。

@javax.persistence.PostLoad:加載後。

@javax.persistence.PrePersist:持久化前。

@javax.persistence.PostPersist:持久化後。

@javax.persistence.PreUpdate:更新前。

@javax.persistence.PostUpdate:更新後。

@javax.persistence.PreRemove:刪除前。

@javax.persistence.PostRemove:刪除後。

複製代碼

1)數據庫查詢

@PostLoad事件在下列狀況下觸發:

執行EntityManager.find()或getreference()方法載入一個實體後。

執行JPQL查詢後。

EntityManager.refresh()方法被調用後。

2)數據庫插入

@PrePersist和@PostPersist事件在實體對象插入到數據庫的過程當中發生:

@PrePersist事件在調用persist()方法後馬上發生,此時的數據尚未真正插入進數據庫。

@PostPersist事件在數據已經插入進數據庫後發生。

3)數據庫更新

@PreUpdate和@PostUpdate事件的觸發由更新實體引發:

@PreUpdate事件在實體的狀態同步到數據庫以前觸發,此時的數據尚未真正更新到數據庫。

@PostUpdate事件在實體的狀態同步到數據庫以後觸發,同步在事務提交時發生。

4)數據庫刪除

@PreRemove和@PostRemove事件的觸發由刪除實體引發:

@PreRemove事件在實體從數據庫刪除以前觸發,即在調用remove()方法刪除時發生,此時的數據尚未真正從數據庫中刪除。

@PostRemove事件在實體從數據庫中刪除後觸發。

@NoArgsConstructor & @AllArgsConstructor(lombok)

@NoArgsConstructor,提供一個無參的構造方法。

@AllArgsConstructor,提供一個全參的構造方法。

@Configuration & @bean1.@Configuration標註在類上,至關於把該類做爲spring的xml配置文件中的<beans>,做用爲:配置spring容器(應用上下文)

複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 @Configuration
  4 public class TestConfiguration {
  5     public TestConfiguration(){
  6         System.out.println("spring容器啓動初始化。。。");
  7     }
  8 }
複製代碼
至關於:
複製代碼
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  4     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
  5     xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
  6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  8         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
  9         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
 10         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
 11         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
 12         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
 13 
 14 
 15 </beans>
複製代碼
主方法進行測試:
複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 public class TestMain {
  4     public static void main(String[] args) {
  5 
  6         //@Configuration註解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContext
  7         ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
  8 
  9         //若是加載spring-context.xml文件:
 10         //ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
 11     }
 12 }
複製代碼

從運行主方法結果能夠看出,spring容器已經啓動了:

  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標註在方法上(返回某個實例的方法),等價於spring的xml配置文件中的<bean>,做用爲:註冊bean對象

bean類:

複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 public class TestBean {
  4 
  5     public void sayHello(){
  6         System.out.println("TestBean sayHello...");
  7     }
  8 
  9     public String toString(){
 10         return "username:"+this.username+",url:"+this.url+",password:"+this.password;
 11     }
 12 
 13     public void start(){
 14         System.out.println("TestBean 初始化。。。");
 15     }
 16 
 17     public void cleanUp(){
 18         System.out.println("TestBean 銷燬。。。");
 19     }
 20 }
複製代碼

配置類:

複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 @Configuration
  4 public class TestConfiguration {
  5         public TestConfiguration(){
  6             System.out.println("spring容器啓動初始化。。。");
  7         }
  8 
  9     //@Bean註解註冊bean,同時能夠指定初始化和銷燬方法
 10     //@Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
 11     @Bean
 12     @Scope("prototype")
 13     public TestBean testBean() {
 14         return new TestBean();
 15     }
 16 }
複製代碼

主方法測試類:

複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 public class TestMain {
  4     public static void main(String[] args) {
  5         ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
  6         //獲取bean
  7         TestBean tb = context.getBean("testBean");
  8         tb.sayHello();
  9     }
 10 }
複製代碼

注:
(1)、@Bean註解在返回實例的方法上,若是未經過@Bean指定bean的名稱,則默認與標註的方法名相同;
(2)、@Bean註解默認做用域爲單例singleton做用域,可經過@Scope(「prototype」)設置爲原型做用域;
(3)、既然@Bean的做用是註冊bean對象,那麼徹底可使用@Component、@Controller、@Service、@Ripository等註解註冊bean,固然須要配置@ComponentScan註解進行自動掃描。

bean類:

複製代碼
  1 package com.test.spring.support.configuration;
  2 
  3 //添加註冊bean的註解
  4 @Component
  5 public class TestBean {
  6 
  7     public void sayHello(){
  8         System.out.println("TestBean sayHello...");
  9     }
 10 
 11     public String toString(){
 12         return "username:"+this.username+",url:"+this.url+",password:"+this.password;
 13     }
 14 }
複製代碼

配置類:

複製代碼
  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對象:

複製代碼
  1 public class TestMain {
  2     public static void main(String[] args) {
  3         ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
  4         //獲取bean
  5         TestBean tb = context.getBean("testBean");
  6         tb.sayHello();
  7     }
  8 }
複製代碼

sayHello()方法都被正常調用。

使用@Configuration註解來代替Spring的bean配置

下面是一個典型的Spring配置文件(application-config.xml):

複製代碼
  1 <beans>
  2         <bean id="orderService" class="com.acme.OrderService"/>
  3                 <constructor-arg ref="orderRepository"/>
  4         </bean>
  5         <bean id="orderRepository" class="com.acme.OrderRepository"/>
  6                 <constructor-arg ref="dataSource"/>
  7         </bean>
  8 </beans>
複製代碼

而後你就能夠像這樣來使用是bean了:

  1 ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
  2 OrderService orderService = (OrderService) ctx.getBean("orderService");

如今Spring Java Configuration這個項目提供了一種經過java代碼來裝配bean的方案:

複製代碼
  1 @Configuration
  2 public class ApplicationConfig {
  3 
  4         public @Bean OrderService orderService() {
  5                 return new OrderService(orderRepository());
  6         }
  7 
  8         public @Bean OrderRepository orderRepository() {
  9                 return new OrderRepository(dataSource());
 10         }
 11 
 12         public @Bean DataSource dataSource() {
 13                 // instantiate and return an new DataSource … 
 14         }
 15 }
複製代碼

而後你就能夠像這樣來使用是bean了:

  1 JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
  2 OrderService orderService = ctx.getBean(OrderService.class);

這麼作有什麼好處呢?

     1.使用純java代碼,不在須要xml

     2.在配置中也可享受OO帶來的好處(面向對象)

     3.類型安全對重構也能提供良好的支持

     4.減小複雜配置文件的同時依舊能享受到全部springIoC容器提供的功能

相關文章
相關標籤/搜索