簡體   English   中英

如何使用Spring Boot加載外部配置?

[英]How to load an external configuration with Spring Boot?

我目前正在學習如何使用Spring Boot。 到目前為止,我從未使用像Spring這樣的框架並直接使用文件(FileInputStream等)

所以情況就是這樣:我有一些動態配置值,比如OAuth令牌。 我想在我的應用程序中使用它們,但我不知道如何用Spring實現這一點。

這是一些代碼,以明確我正在搜索的內容:

@Config("app.yaml")
public class Test {
    @Value("app.token")
    private String token;
    private IClient client;

    public Test(String token) {
        this.client = ClientFactory.build(token).login();
    }
}

當然,這個例子很簡單。 在這里,我想從YAML配置文件中動態獲取值“token”。 該文件必須可供用戶訪問且不包含在JAR文件中。

我還發現doc: https//docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html但我現在知道如何將它應用到我的項目中。

我怎么能得到這個? 先感謝您 :)

編輯:

以下是我的代碼的一些部分:

WatchdogBootstrap.java

package de.onkelmorph.watchdog;

import org.springframework.boot.Banner.Mode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:Beans.xml")
public class WatchdogBootstrap {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(WatchdogBeans.class);
        app.setBannerMode(Mode.OFF);
        app.setWebEnvironment(false);
        app.run(args);
    }
}

Beans.xml (位於默認包中)

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config></context:annotation-config>
</beans>

Watchdog.java

package de.onkelmorph.watchdog;

// Imports ...

@Component
@PropertySource("file:/watchdog.yml")
public class Watchdog {
    // ...

    // Configuration
    @Value("${watchdog.token}")
    private String token;

    public Watchdog() {
        System.out.println(this.token);
        System.exit(0);
    }

    // ...
}

watchdog.yml (位於src / main / resources)

watchdog:
  token: fghaepoghaporghaerg

首先,你的Test類應該用@Component注釋,以便它在春天之前注冊為bean(同時確保你的所有類都在你的主包下 - 主包是用@SpringBootApplication注釋的類的@SpringBootApplication居住)。

現在你應該將所有屬性移動到application.ymlsrc/main/resources/application.yml ),這是由spring boot自動選取的(注意它應該是.yml而不是.yaml或注冊一個自定義的PropertySourcesPlaceholderConfigurer

PropertySourcesPlaceholderConfigurer示例:

@Bean
public static PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer() throws IOException {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    MutablePropertySources propertySources = new MutablePropertySources();
    Resource resource = new DefaultResourceLoader().getResource("classpath:application.yml");
    YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
    PropertySource<?> yamlProperties = sourceLoader.load("yamlProperties", resource, null);
    propertySources.addFirst(yamlProperties);
    configurer.setPropertySources(propertySources);
    return configurer;
}

現在你的屬性應該被加載到spring的環境中,並且它們可以通過@Value注入你的bean。

你基本上有三個簡單的選擇。

  1. 使用application.properties是Springs內部配置文件。
  2. 使用--spring.config.name作為VM參數加載您自己的配置文件。
  3. 您可以使用@PropertySource加載內部或外部配置。 @PropertySource僅適用於.properties配置文件。 目前有一個開放的Jira票證來實現yaml支持。 您可以按照以下步驟進行操作: https//jira.spring.io/browse/SPR-13912

請注意,如果您使用包含公共密鑰的多個yaml和/或屬性文件,它將始終使用最后加載的密鑰的定義。 這就是下面的示例使用兩個不同的鍵的原因。 如果它使用相同的鍵,那么它將打印兩次PROPERTIES FILE

簡短的代碼片段:

@Component
@PropertySource("file:/path/to/config/app.properties")
class Address{

    @Value("${addr.street}")
    private String street;

    @Value("${addr.city}")
    private String city;
}

app.properties

addr.street=Abbey Road
addr.city=London

廣泛的例子

DemoApplication.java

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(DemoApplication.class, args);

        //Call class with properties
        context.getBean(WatchdogProperties.class).test();
        //Call class with yaml
        context.getBean(WatchdogYaml.class).test();
    }

    //Define configuration file for yaml
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
      PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
      YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
      yaml.setResources(new ClassPathResource("watchdog.yml"));
      propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
      return propertySourcesPlaceholderConfigurer;
    }
}

WatchdogProperties.java

@Component
//PropertySource only works for .properties files
@PropertySource("classpath:watchdog.properties")
public class WatchdogProperties{
    //Notice the key name is not the same as the yaml key
    @Value("${watchdog.prop.token}")
    private String token;

    public void test(){
        System.out.println(token);
    }
}

WatchdogYaml.java

@Component
class WatchdogYaml{
    //Notice the key name is not the same as the properties key
    @Value("${watchdog.token}")
    private String token;

    public void test(){
        System.out.println(token);
    }
}

屬性和Yaml文件這兩個文件都位於src/main/resources

watchdog.yml:

watchdog:
  token: YAML FILE

watchdog.properties:

watchdog.prop.token=PROPERTIES FILE

產量

PROPERTIES FILE
YAML FILE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM