springboot读取jar外部配置文件,spring mybatis配置文件(springboot读取jar包外的配置文件)

SpringBoot读取jar外部配置文件,可以通过以下几种方式实现:

1、使用@PropertySource注解加载外部配置文件

springboot读取jar外部配置文件,spring mybatis配置文件(springboot读取jar包外的配置文件)

在SpringBoot项目中,可以使用@PropertySource注解来加载外部的配置文件,假设我们有一个名为application-external.properties的外部配置文件,可以将其放置在项目的resources/external目录下,然后在需要加载该配置文件的类上添加@PropertySource注解:

import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:application-external.properties")
public class ExternalConfig {
}

2、使用Environment对象获取外部配置文件中的属性值

通过注入Environment对象,可以直接获取到外部配置文件中的属性值,假设我们想要获取application-external.properties文件中名为my.property的属性值,可以这样做:

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class ExternalConfig {
    private final Environment environment;
    public ExternalConfig(Environment environment) {
        this.environment = environment;
    }
    public String getMyProperty() {
        return environment.getProperty("my.property");
    }
}

3、使用ResourceLoader加载外部配置文件

通过注入ResourceLoader对象,可以动态地加载外部配置文件,假设我们想要动态地加载一个名为application-external.properties的外部配置文件,可以这样做:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Properties;
@Component
public class ExternalConfig {
    @Autowired
    private ResourceLoader resourceLoader;
    public Properties loadExternalProperties(String path) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + path);
        Properties properties = new Properties();
        properties.load(resource.getInputStream());
        return properties;
    }
}

4、将外部配置文件放在src/main/resources/META-INF/spring.factories文件中,并指定其内容类型为text/plain,然后在启动类上添加@EnableConfigurationProperties注解和自定义配置类的注解,如@ConfigurationProperties(prefix = "my"),即可实现自动装配,这种方式适用于将外部配置文件与Spring Boot项目的其他组件进行集成。

原创文章,作者:酷盾叔,如若转载,请注明出处:https://www.kdun.com/ask/93913.html

(0)
酷盾叔订阅
上一篇 2023-12-14 17:48
下一篇 2023-12-14 17:51

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入