Spring实战读书笔记(二):在Java中进行显示配置

  • Post author:
  • Post category: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一节的内容相差无异。

所以这部分可以省略。留待读者自行改造。

以上。


版权声明:本文为huangpin815原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。