在软件开发过程中,经常会使用到配置文件,本文基于SpingBoot如何引入相关的配置项的几种常规方式。
在需要引入配置信息的Bean类中,使用@Value注解可以方便引入对应配置项的内容,但需要将引入配置项的key全名填写正确。
application.properties
userproperties.name=this is my user
application.yml
useryml:
name: this is my user
@Component
public class UserService{
@Value("${userproperties.name}")
private String name;
@Value("${useryml.name}")
private String nameyml;
...
}
如上在userService中通过注解@Value则可以引入
注解ConfigurationProperties是使用配置最常见的一种方法,该注解可以统一指定配置的前缀,默认拼接前缀和字段名作为配置项的key,避免手动埴写配置Key名称。
@Setter
@Component
@ConfigurationProperties(prefix = "userproperties")
public class UserAppConfig{
private String name;
private String age;
private String email;
private String sex;
}
需要注意的是该类中需要提供配置项的set方法,以及标注为Component,当然更多地使用@Configuration取代,其里面也用到了Component。如果不标注为Component,则需要在启动类上显示指定配置类(可以指定多个),通过注解:
EnableConfigurationProperties(UserAppConfig.class)
但需要注意的是UserAppConfig可以通过@Autowired引用,但注意此时无法通过名字获得到Bean。
默认的配置文件,最终都会统一在Environment进行维护,可以通过其提供的getProperty获得具体的配置值。
@Autowired
private Environment environment;
@PostConstruct
public void postConstruct() {
String property = environment.getProperty("userproperties.name");
System.out.println("userproperties.name====" + property);
}
使用注解可以指定配置文件的路径和名称而不一定是默认配置文件,如下:
@Component
@PropertySource(value = "classpath:config.properties")
@Data
public class MyConfigBean {
@Value("${myconfig.name}")
private String name;
同样地如与@ConfigurationProperties配置,则可以避免配置项key的完整名称填写。
但需要注意的是@PropertySource是不支持yaml读取的。需要如下修改:
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
public class CommPropertyResourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource
resource) throws IOException {
String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) {
List<org.springframework.core.env.PropertySource<?>> yamlSources =
new YamlPropertySourceLoader().load(resourceName, resource.getResource());
return yamlSources.get(0);
} else {
return new DefaultPropertySourceFactory()
.createPropertySource(name, resource);
}
}
}
在需要读取yaml的时候,要增加factory参数
@PropertySource(value = { "classpath:configValue.yml" },
factory = CommPropertyResourceFactory.class)