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

原本项目中有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}"

看了https://blog.youkuaiyun.com/hannover100/article/details/78124660该贴,知道是由于多个配置文件导致的问题,再在启动类加入

 @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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值