【问题标题】:How to read spring boot application property information inside the library如何读取库内的spring boot应用程序属性信息
【发布时间】:2021-08-23 07:09:50
【问题描述】:

我正在为我们的项目开发一个通用库。这是一个 Maven 项目。现在它没有任何与Spring相关的依赖。

我在 Spring boot maven 项目中包含上述库作为依赖项。

当 Spring Boot 应用程序运行时,我需要从公共库中的 Spring Boot application.properties 中读取值。

假设我在 application.properties 中有环境键。

环境 = 舞台

我需要图书馆内环境的价值。

【问题讨论】:

  • 我可能会建议创建一个可感知弹簧的包装器模块(可能是弹簧启动自动配置)。这样,您的库是独立于 spring 的,但可能以编程方式接受配置值,并且您的 spring 模块会自动获取 spring 属性。我认为你想要的最后一件事是让库本身直接从 application.properties 中读取。

标签: java spring spring-boot


【解决方案1】:

我建议,您应该在库中添加配置以接受外部配置。您可以在库中创建一个Configuration 类,该类将存储所有必需的属性。然后您可以创建Configuration 的实例并将其提供给您库中的其他类。我看到许多图书馆都遵循相同的模式。我们以需要 Elasticsearch URL 的 Elasticsearch 客户端为例:

Elasticsearch 客户端

String elasticsearchUrl = environment.getRequiredProperty("elasticsearch-url");

ClientConfiguration clientConfiguration =
    ClientConfiguration.builder().connectedTo(elasticsearchUrl).build();
RestHighLevelClient client = RestClients.create(clientConfiguration).rest();

在上面的示例中,elasticsearch-url 通过application.properties 文件被接受,然后提供给 Elasticsearch 客户端库。

【讨论】:

    【解决方案2】:

    在 Spring Boot 应用程序中

    @SpringBootApplication
    

    公共类 ExampleMsApplication 实现 ApplicationRunner {

    @Value("${props.env}")
    private String env;
    
    public static void main(String[] args) {
        SpringApplication.run(ExampleMsApplication.class, args);
    }
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.setProperty("env", env);
    }
    

    }

    application.properties

    props.env=local

    在库中需要的地方,我使用下面的代码。无论我使用 System.setProperty 在 Spring Boot 应用程序中设置什么,我都可以使用 System.getProperty

    System.getProperty("env")

    【讨论】:

      【解决方案3】:

      您可以创建一个@ConfigurationProperties 类并创建具有以下属性的/resources/META-INF/spring.factories 文件:-

      org.springframework.boot.autoconfigure.EnableAutoConfiguration=你的类的完整分类名称

      【讨论】:

        猜你喜欢
        • 2014-01-07
        • 1970-01-01
        • 2017-06-17
        • 2020-01-22
        • 2021-03-22
        • 2017-06-26
        • 2021-03-12
        • 2022-01-21
        • 1970-01-01
        相关资源
        最近更新 更多