@RefreshScope не работает с внешними конфигурационными файлами - PullRequest
0 голосов
/ 30 января 2020

Я добавил следующие зависимости в свой pom, чтобы я мог использовать Spring Cloud

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter</artifactId>
    </dependency>

  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Добавил spring-cloud.version в качестве Finchley.RELEASE

Это бин, который я намерены обновить sh:

@Component
@ConfigurationProperties(ignoreUnknownFields = true,prefix="global")
@PropertySource(value = "${spring.config.location}")
@Getter
@Setter
@Validated
@RefreshScope
public class GeneralProperties {
    private String mode;
}

Доступ к bean-компоненту в моем контроллере:

@RestController
@RequestMapping
@RefreshScope
public class AppController {

    private static final AnalyticsLogger LOGGER = AnalyticsLoggerFactory
            .getLogger(AppController.class);

    @Autowired
    SimulatorRequestProcessor simulatorRequestProcessor;

    @Autowired
    GeneralProperties generalProperties;

    @ResponseBody
    @PostMapping(value = "/api/mock-getdata", produces = "application/json")
    public String fetchResponseBasedOnMode(@RequestHeader HttpHeaders headers,
            @RequestBody String request) {
        String response = null;
        LOGGER.info("color: "+color);
        switch (generalProperties.getMode()) {
         //code

Свойства, установленные в конфигурации приложения:

 spring.config.location=file:///var/lib/data/demo/config/generalConfig.properties
 management.endpoints.web.exposure.include=refresh

Невозможно обновить sh значение режима. Может кто-то указать на ошибку в этом коде. Мои файлы свойств находятся в папке, которая не зафиксирована в git, поэтому я не использую spring-cloud-config.

1 Ответ

0 голосов
/ 30 января 2020

Поместите это в src/main/resources/application.properties

management.endpoints.web.exposure.include=*

Запустите эту программу с этим аргументом --spring.config.additional-location=/tmp/application.properties

package com.example.demorefreshscopeexternalfile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.style.ToStringCreator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableConfigurationProperties(DemorefreshscopeexternalfileApplication.MyProps.class)
public class DemorefreshscopeexternalfileApplication {

    @Autowired
    MyProps props;

    @RequestMapping
    public String message() {
        return props.getMessage();
    }

    public static void main(String[] args) {
        SpringApplication.run(DemorefreshscopeexternalfileApplication.class, args);
    }

    @ConfigurationProperties("my")
    public static class MyProps {
        private String message;

        public String getMessage() {
            return this.message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        @Override
        public String toString() {
            return new ToStringCreator(this)
                    .append("message", message)
                    .toString();

        }
    }
}

содержимое /tmp/application.properties

my.message=message from /tmp

можно обновить http://localhost:8080

/tmp/application.properties, отправить сообщение на /actuator/refresh и снова просмотреть 8080, и вы увидите обновленные значения.

Построен с загрузкой 2.2.4 и Hoxton .SR1

См. https://docs.spring.io/spring-boot/docs/2.2.4.RELEASE/reference/html/appendix-application-properties.html#common -application-properties для spring.config.* и их значение.

...