SpringBoot配置文件详解

SpringBoot自定义配置文件内容获取

SpringBoot配置文件内容获取

前提

  1. 添加以下依赖
1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

新建实体类获取application.yml/applicaiton.properties配置文件内容

  1. @Component@ConfigurationProperties 注解
application.yml配置文件
1
2
3
4
5
server:
port: 9099
user:
name: markdown
age: 10
实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "user")
public class UserConfig implements Serializable {

private String name;

private String age;

/** 省略get/set 方法 */
}
测试类
  • 测试是否能够正确获取配置文件内容
1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserConfigTest {

@Autowired
private UserConfig properties;

@Test
public void propertiesTest() {
System.out.println(properties.name() + "\t" + properties.getAge());
}
}
  1. @Component@Value 注解
  • application.yml/application.properties 文件内容不变
实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
public class User2Config implements Serializable {

@Value(value = "${user.url}")
private String name;

@Value(value = "${user.age}")
private String age;

/** 省略get/set 方法 */
}
测试类
1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class User2ConfigTest {

@Autowired
private User2Config properties;

@Test
public void propertiesTest() {
System.out.println(properties.name() + "\t" + properties.getAge());
}
}

创建实体类获取自定义(xx.properties)配置文件内容

  • 注: 自定义配置文件最好还是使用.properties格式的文件,注解方式还不支持手动加载.yml格式文件的功能
  1. @Configuration注解替换@Component注解,@PropertySource("classpath:xx.properties")
创建自定义配置文件my.properties
1
2
3
# 高德——地理编码
geo.url= http://restapi.amap.com/v3/geocode/geo
geo.key= 11111
实体类
1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
@PropertySource("classpath:geocode.properties")
public class GeocodingProperties {

@Value(value = "${geo.url}")
private String url;

@Value(value = "${geo.key}")
private String name;

/*省略get/set方法*/
}
测试类
1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class GeoCodingUtilTest {

@Autowired
private GeocodingProperties properties;

@Test
public void propertiesTest() {
System.out.println(properties.getKey() + "\t" + properties.getUrl());
}
}
  • 配置文件可创建在resource中的文件夹下,使用相对根目录的文件夹即可(默认resources/为根目录)

@Configuration@PropertySource@ConfigurationProperties

  • 注: 使用@configuration@ConfigurationProperties注解时,需要在启动类(Application.java)中增加@EnableConfigurationProperties(PhoneProperties.class)注解。

配置文件

  • 配置文件路径resources/properties/phone.properties")
1
2
3
phone.model= iPhone 8 Plus
phone.price= 5266
phone.system= iOS 12.2.x

启动类

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableConfigurationProperties(PhoneProperties.class)
public class Application {

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

}

配置文件实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@PropertySource(value = "classpath:properties/phone.properties")
@ConfigurationProperties(prefix = "phone")
public class PhoneProperties {

private String model;

private Double price;

private String system;

/*省略get/set、toString()方法*/
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringRunner.class)
@SpringBootTest
public class PhonePropertiesTest {

@Autowired
private PhoneProperties phoneProperties;

@Test
public void phonePropertiesTest() {
System.out.println(phoneProperties.toString());
}

}

使用Environment方法获取配置文件的值

注解说明

  • @Component

    1. 将普通的pojo实例化到Spring容器中,相当于xml配置文件中的<bean id="" class=""/>;

    2. 泛指组件,当组件不好归类的的时候,可以使用这个组件。

  • @Configutration

    1. 用于定义配置类;

    2. @Configuration 中所有带@Bean注解的方法都会被动态代理,因此调用该方法返回的都是同一个实例。

    3. @Component@Component 区别详细介绍,Spring @Configuration 和 @Component区别

  • @PropertySource

    1. 通过注解的方式将properties配置文件中的值存储到SpringEnviroment中,Environment接口提供方法去读取配置文件中的值,参数时properties文件中定义的key值。
  • @ConfigurationProperties

    1. 将同类的配置信息封装成实体类;

    2. @ConfigurationProperties一起使用时,需要在启动类增加@EnableConfigurationProperties注解并制定该实体类为配置类 或 使用@Component注解替代@Configuration注解。

  • @Value

    1. @value属性名,在属性名上添加该注解;

    2. 默认读取的配置文件是application.yml/application.properties,可在@RestController/@Controller中获取配置。

常见问题

在非Controller 中无法获取配置类 或 注入相应注解
  • 在工具类中,获取RestTemplate注解以及自定义配置文件为例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Point 1: 使用类注解`@Conponent`
@Component
public class GeoCodingUtil {

@Autowired
private RestTemplate restTemplate;

@Autowired
private GeocodingProperties properties;

// Point 2: 将本类设置为属性
private static GeoCodingUtil geoCodingUtil;

@PostConstruct
private void init() {
geoCodingUtil = this;
geoCodingUtil.properties = this.properties;
geoCodingUtil.restTemplate = this.restTemplate;
}

// 调用示例
public void getProperties(){
System.out.println(geoCodingUtil.properties.getUrl());
}

}

注解说明

  • @PostConstruct

    1. @PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Servletinit()方法。被@PostContruct修饰的方法会在构造函数之后,init()方法之前运行。
    2. @PostContruct 注释的init()方法,会在@Configuration配置之前运行。例如: 在执行预加载函数前,需要加载配置项则需要implements CommandLineRunner接口,若使用@PostContruct则只有在init()方法执行完才能获取@Configuration注解的自定义配置项。