spring 文件applicationContext.xml 配置转为spring boot加载

568 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第十二天,点击查看活动详情


公司有需求将普通项目拆分为微服务,使用springcloud。

将普通sping项目转为springboot项目后,原本的xml文件也想要改为分布式服务的配置方式,去掉之前的如applicationContext.xml等文件。

原本项目中有applicationContext.xml文件

<!-- 属性文件读入 -->
<bean id="propertyConfigurer" class="XX.XX.XX.SpringPropertiesUtils">
        <property name="locations">
                <list>
                        <value>classpath*:config/*.properties</value>
                </list>
        </property>
</bean>

转为springboot 项目后不想继续使用xml文件加载配置文件,则在启动类中加入下面的配置信息

@Bean
public SpringPropertiesUtils getSpringProUtils() {
    return new SpringPropertiesUtils();
}

使用这种方式加载后,项目报如下异常:

legalArgumentException: Could not resolve placeholder 'jdbc.driver-class-name' in value "${jdbc.driver-class-name}"

查看资料后,知道是由于多个配置文件导致的问题,再在启动类加入如下的配置

 @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
        c.setIgnoreUnresolvablePlaceholders(true);
        return c;
    }

后来发现properties文件的属性没有注入到想要加载的类里面,后来新建了一个config专门加载这些文件

@Configuration
public class PropertiesConfig {
 
    @Bean(name="propertyConfigurer")
    @ConfigurationProperties(prefix = "XX.XX.XX")
    public SpringPropertiesUtils SpringPropertiesUtils(){
        SpringPropertiesUtils springPropertiesUtils = new SpringPropertiesUtils();
        springPropertiesUtils.setLocations(new ClassPathResource("config/basic.properties"));
        return springPropertiesUtils;
    }
}

但properties文件好像只能一个一个加载,尝试找到可以一次全部加载的方法。

21.01.26新增

根据不同的启动命令,读取不同的配置文件:

@Bean("propertyConfigurer")
@DependsOn("springContextHolder")
public SpringPropertiesUtils SpringPropertiesUtils(){
    SpringPropertiesUtils springPropertiesUtils = new SpringPropertiesUtils();
    String active = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[0];
    if (active.equals("dev")) {
        springPropertiesUtils.setLocations(
                new ClassPathResource("application.properties"),
                new ClassPathResource("application-dev.properties")
        );
    } else {
        springPropertiesUtils.setLocations(
                new ClassPathResource("application.properties"),
                new ClassPathResource("application-prod.properties")
        );
    }
    return springPropertiesUtils;
}

当启动多个端口时,获取当前服务的端口号:

  @Bean("getPortConfigurer")
    public static String getPort(){
        String port = SpringContextHolder.getApplicationContext().getEnvironment().getProperty("server.port");
        return port;
  }

再次启动,发现项目运行成功,对应的配置文件也都加载成功,项目部署时根据项目部署环境指定加载对应配置文件,避免加载文件不正确。