SpringBoot第三節(thymeleaf的配置與SpringBoot注解大全)


Springboot默認是不支持JSP的,默認使用thymeleaf模板引擎。所以這里介紹一下Springboot使用Thymeleaf的實例以及遇到的問題。

1.配置與使用

  1.1:在application.properties文件中增加Thymeleaf模板的配置。

  關閉thymeleaf的緩存,不然在開發過程中修改頁面不會立刻生效需要重啟,生產可配置為true

#關閉thymeleaf的緩存,不然在開發過程中修改頁面不會立刻生效需要重啟,生產可配置為true
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/web/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

  這些配置不是必須的,如果配置了會覆蓋默認的。

2.在pom.xml中添加以下依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.編寫一個測試的Controllert

@Controller
public class Passowdsad {
    @RequestMapping("/toIndex")
    public String index(){
        return "index";
    }
}

可以看到SpringBoot的Controller與普通的Controller是一樣的

4.編寫index.html

默認情況下:
spring-boot項目靜態文件目錄:/src/java/resources/static (比如:js、css、img等靜態資源)
spring-boot項目模板文件目錄:/src/java/resources/templates

<!DOCTYPE html >
<!--基於Thymeleaf的模板引擎-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="img/timg.jpg"/>
</body>
</html>

5.直接運行訪問

localhost:9090/toIndex

效果如下

 

 

 

一、注解列表如下(配備了完善的釋義)------(可采用ctrl+F 來進行搜索哦~~~~)

 

@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中

 

@ComponentScan:讓spring Boot掃描到Configuration類並把它加入到程序上下文。

 

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

 

@EnableAutoConfiguration :自動配置。

 

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

 

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

 

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

 

@Autowired:自動導入。

 

@PathVariable:獲取參數。

 

@JsonBackReference:解決嵌套外鏈問題。

 

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

 

二、注解詳解(配合代碼段詳細解釋更直觀明了)

 

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

 

1 package com.example.myproject;
2 import org.springframework.boot.SpringApplication;
3 import org.springframework.boot.autoconfigure.SpringBootApplication;

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;

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;

3 import org.springframework.web.bind.annotation.RequestMapping;
4 import org.springframework.web.bind.annotation.RestController;


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:表示將該類自動發現掃描組件。個人理解相當於,如果掃描到有@Component、@Controller、@Service等這些注解的類,並注冊為Bean,可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,並結合@Autowired注解導入。可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,並結合@Autowired注解導入。如果沒有配置的話,Spring Boot會掃描啟動類所在包下以及子包下的使用了@Service,@Repository等注解的類。

 

@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干類似的事。

 

三、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配置文件中的一對一,一對多,多對一。

 

四、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 }
參數與大括號里的名字一樣要相同。

 

五、全局異常處理

 

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

 

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

 

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

 

@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 方法

3 @Setter:注解在屬性上;為屬性提供 setting 方法

5 @Getter:注解在屬性上;為屬性提供 getting 方法

7 @Log4j2 :注解在類上;為類提供一個 屬性名為log 的 log4j 日志對象,和@Log4j注解類似

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 & @bean
1.@Configuration標注在類上,相當於把該類作為spring的xml配置文件中的
<beans>
,作用為:配置spring容器(應用上下文)
1 package com.test.spring.support.configuration;

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;

3 public class TestMain {
4 public static void main(String[] args) {

6 //@Configuration注解的spring容器加載方式,用AnnotationConfigApplicationContext替換ClassPathXmlApplicationContext
7 ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

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;

3 public class TestBean {

5 public void sayHello(){
6 System.out.println("TestBean sayHello...");
7 }

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;

3 @Configuration
4 public class TestConfiguration {
5 public TestConfiguration(){
6 System.out.println("spring容器啟動初始化。。。");
7 }

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;

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;

3 //添加注冊bean的注解
4 @Component
5 public class TestBean {

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 }

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 {

4 public @Bean OrderService orderService() {
5 return new OrderService(orderRepository());
6 }

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.在配置中也可享受面向對象帶來的好處

 

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

 

     4.減少復雜配置文件的同時亦能享受到springIoC容器提供的功能

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM