spring boot与配置文件那些事

前言

本文记录spring boot读取配置文件的方式和本人遇到过的问题。

如何读配置文件

一、注解的方式

@ConfigurationProperties
可以把配置文件注入实体类
使用@ConfigurationProperties(prefix = “xxx”)

ConfigurationProperties注解的优缺点
一、可以从配置文件中批量注入属性;
二、支持获取复杂的数据类型;
三、对属性名匹配的要求较低,比如user-name,user_name,userName,USER_NAME都可以取值;
四、支持JAVA的JSR303数据校验;
五、缺点是不支持强大的SpEL表达式;

@Value
可以读取配置文件中的某一项
@PropertySource
如果有多个配置文件,可以用@PropertySource读取
一般application.properties优先级最高

二、通过获取环境变量来获取配置参数

ConfigurableApplicationContext ctx = SpringApplication.run(SpringbootPropertiesApplication.class, args);
ctx.getEnvironment().getProperty("db.link.url")

三、使用PropertiesLoaderUtils

可参考
https://blog.csdn.net/thc1987/article/details/78789426

四、如何读取自定义的配置文件

  1. 在resource中新建.properties文件
    在resource目录下新建一个config文件夹,然后新建一个.properties文件放在该文件夹下。

  2. 编写配置文件

    remote.uploadFilesUrl=/resource/files/
    remote.uploadPicUrl=/resource/pic/

  3. 新建一个配置类RemoteProperties.java

    配置如下
     @Configuration
     @ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false)
     @PropertySource("classpath:config/remote.properties")
     @Data
     @Component
     public class RemoteProperties {
         private String uploadFilesUrl;
         private String uploadPicUrl;
     }
    

其中 @Configuration 表明这是一个配置类 @ConfigurationProperties(prefix = “remote”, ignoreUnknownFields = false) 该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。 @PropertySource(“classpath:config/remote.properties”) 配置文件路径 @Data 这个是一个lombok注解,用于生成getter&setter方法,详情请查阅lombok相关资料 @Component 标识为Bean

  1. 如何使用?
    在想要使用配置文件的方法所在类上表上注解EnableConfigurationProperties(RemoteProperties.class) 在想要使用配置文件的方法所在类上表上注解EnableConfigurationProperties(RemoteProperties.class)
    并自动注入
    @Autowired
    RemoteProperties remoteProperties;

在方法中使用 remoteProperties.getUploadFilesUrl()就可以拿到配置内容了。

@EnableConfigurationProperties(RemoteProperties.class)
@RestController
public class TestService{
    @Autowired
    RemoteProperties remoteProperties;

    public void test(){
        String str = remoteProperties.getUploadFilesUrl();
        System.out.println(str);
    }
}

五、遇到过的问题(持续更新)

错误:

2018-11-19 22:14:24.301  INFO 12743 --- [           main] c.d.envoy.service.EngineServiceTest      : Starting EngineServiceTest on shulankejideMacBook-Air-2.local with PID 12743 (started by jacobzheng in /Users/jacobzheng/Documents/work/code/envoy)
2018-11-19 22:14:24.303  INFO 12743 --- [           main] c.d.envoy.service.EngineServiceTest      : The following profiles are active: noRegister
2018-11-19 22:14:25.677  WARN 12743 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.dtwave.envoy]' package. Please check your configuration.
2018-11-19 22:14:26.568  WARN 12743 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'envoyConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'service.citicPrefix' in value "${service.citicPrefix}"
2018-11-19 22:14:26.585  INFO 12743 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-11-19 22:14:26.598 ERROR 12743 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'envoyConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'service.citicPrefix' in value "${service.citicPrefix}"

在读配置文件的地方加入
@PropertySource(“classpath:application.properties”)

错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
@EnableAutoConfiguration(exclude = {
		DataSourceAutoConfiguration.class,
		MybatisAutoConfiguration.class,
		DataSourceTransactionManagerAutoConfiguration.class
})


    engineService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.dtwave.envoy.service.EngineService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test: [DefaultTestContext@21129f1f testClass = EngineServiceTest, testInstance = com.dtwave.envoy.service.EngineServiceTest@16a35bd, testMethod = getEngineSimpleInfoList@EngineServiceTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@5a9f4771 testClass = EngineServiceTest, locations = '{}', classes = '{class com.dtwave.envoy.EnvoyApplication, class com.dtwave.envoy.EnvoyApplication}', contextInitializerClasses = '[]', activeProfiles = '{noRegister}', propertySourceLocations = '{}', propertySourceProperti

猜你喜欢

转载自blog.csdn.net/Jacob_Zheng/article/details/84784891