Spring實戰讀書筆記(二):在Java中進行顯示配置

讀書筆記中涉及到的書可以從這個repo下載

1 背景

我們可以通過3種方式裝配bean,分別是:

  1. 在XML中進行顯式配置
  2. 在Java中進行顯示配置
  3. 隱式的bean發現機制和自動裝配

這篇博文講第2種方式

2 在Java中進行顯示配置

還是以一個項目(地址:https://github.com/AChaoZJU/Vue-Spring-Boot-Get-Started)爲例,來描述通過在Java中進行顯示配置,以裝配bean。
這個項目的分支介紹如下:

  1. master:隱式的bean發現機制和自動裝配
  2. JavaConfig: 在Java中進行顯示配置,這個分支對master進行了一些修改,是博文結束後代碼的樣子

2.0 移除@Service

// class FileSystemStorageService
// @Service 這個註解需要被移除
public class FileSystemStorageService implements StorageService {

  private final Path rootLocation;

  public FileSystemStorageService(StorageProperties properties) {
    this.rootLocation = Paths.get(properties.getLocation());
  }
  ...
  }

如此SpringBoot不能通過組件掃描的方式創建FileSystemStorageService的bean了

2.1 創建Java Config類

@Configuration註解表明這個類是是一個配置類

//BusinessApplication.java
package com.wepay.business;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BusinessApplication {

	public static void main(String[] args) {
		SpringApplication.run(BusinessApplication.class, args);
	}
}

我們的項目使用了Spring Boot的@SpringBootApplication被@SpringBootConfiguration註解,@SpringBootConfiguration被@Configuration註解,所以這是個Java Config類

2.2 聲明簡單的bean

To declare a bean in JavaConfig, you write a method that creates an instance of the desired type and annotate it with @Bean.


package com.wepay.business;

import com.wepay.business.resource.storage.FileSystemStorageService;
import com.wepay.business.resource.storage.StorageProperties;
import com.wepay.business.resource.storage.StorageService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class BusinessApplication {
//增加的代碼起始
	@Bean
  public StorageService fileSystemStorageService(StorageProperties storageProperties) {
	  return new FileSystemStorageService(storageProperties);
  }

//增加的代碼結束
	public static void main(String[] args) {
		SpringApplication.run(BusinessApplication.class, args);
	}
}

The @Bean annotation tells Spring that this method will return an object that should be registered as a bean in the Spring application context. The body of the method contains logic that ultimately results in the creation of the bean instance.

你可能會奇怪爲什麼storageProperties不需要autowire呢?
因爲:

@Autowire lets you inject beans from context to “outside world” where outside world is your application. Since with @Configuration classes you are within "context world ", there is no need to explicitly autowire (lookup bean from context).

詳見:這裏

2.3 使用Java Config注入bean

本來這裏有第3部分:使用Java Config注入bean

要做到這個,實則是將用到fileSystemStorageService bena的GoodResource類也改造成手動創建bean的形式,這其實就是套娃了,和2.2一節的內容相差無異。

所以這部分可以省略。留待讀者自行改造。

以上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章