在相应的Configuration类(Spring Boot)中配置的多个yml文件

问题描述 投票:0回答:1

我在Spring Boot的资源类路径位置中有多个yml文件,例如Spring Boot的以下结构。最初,我只为application-abc.yml编写文件,并且此文件的所有值均已加载到其相应的类中,但是当我在另一个文件中添加了application-xyz.yml时,它也加载到了其相应的配置类中,但是目前,仅在两个配置类中都加载application-xyz.yml的值。因此,需要帮助来在单个构建中配置它们相应的配置文件中两个文件的值:

-src
  -main
     -java
        -packages
          -config
             -ApplicationAbcConfig.java
             -ApplicationConfig.java
             -ApplicationFactory.java
             -ApplicationXyzConfig.java
             -Authentication.java
             -Operations.java
             -Payload.java
             -RequestPayload.java
             -ResponsePayload.java

         -services
             -YmlConfigurationSelection.java

         -resources
            -application.yml
            -application-abc.yml
            -application-xyz.yml

         -MultipleYmlDemoProject.java

application-abc.yml的内容

authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes1
          - attributes2
    response:
      - sequence: 1
        attributes:
          - attributes3
          - attributes4

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes5
          - attributes6
    response:
      - sequence: 1
        attributes:
          - attributes7
          - attributes8

application-xyz.yml的内容

authentication:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes9
          - attributes10
    response:
      - sequence: 1
        attributes:
          - attributes11
          - attributes12

operations:
  name: name
  type: type
  payload:
    request:
      - sequence: 1
        attributes:
          - attributes13
          - attributes14
    response:
      - sequence: 1
        attributes:
          - attributes15
          - attributes16

ApplicationConfig.java的内容

public interface ApplicationConfig {
    public Authentication getAuthentication();

    public void setAuthentication(Authentication authentication);

    public Operations getOperations();

    public void setOperations(Operations operations);
}

**Content of Authentication.java**

public class Authentication {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}

Operations.java的内容

public class Operations {
    private String name;
    private String type;
    private Payload payload;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}

Payload.java的内容

public class Payload {
    private List<RequestPayload> request;
    private List<ResponsePayload> response;

    public List<RequestPayload> getRequest() {
        return request;
    }

    public void setRequest(List<RequestPayload> request) {
        this.request = request;
    }

    public List<ResponsePayload> getResponse() {
        return response;
    }

    public void setResponse(List<ResponsePayload> response) {
        this.response = response;
    }
}

RequestPayload.java的内容

public class RequestPayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}

ResponsePayload.java的内容

public class ResponsePayload {
    private String sequece;
    private List<String> attributes;

    public String getSequece() {
        return sequece;
    }

    public void setSequece(String sequece) {
        this.sequece = sequece;
    }

    public List<String> getAttributes() {
        return attributes;
    }

    public void setAttributes(List<String> attributes) {
        this.attributes = attributes;
    }
}

ApplicationAbcConfig.java的内容

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-abc.yml")
public class ApplicationAbcConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

ApplicationXyzConfig.java的内容

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties
@org.springframework.context.annotation.PropertySource("classpath:application-xyz.yml")
public class ApplicationXyzConfig implements ApplicationConfig, PropertySourceFactory {
    private Authentication authentication;
    private Operations operations;

    @Override
    public Authentication getAuthentication() {
        return authentication;
    }

    @Override
    public void setAuthentication(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public Operations getOperations() {
        return operations;
    }

    @Override
    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

ApplicationFactory.java的内容

@Component
public class ApplicationFactory {
    @Autowired
    private ApplicationAbcConfig applicationAbcConfig;

    @Autowired
    private ApplicationXyzConfig applicationXyzConfig;

    public ApplicationConfig getApplicationPropertiesConfig(String application) {
        if (application.equalsIgnoreCase("abc")) {
            return applicationAbcConfig;
        } else if (application.equalsIgnoreCase("xyz")) {
            return applicationXyzConfig;
        } else {
            return null;
        }
    }
}

YmlConfigurationSelection.java的内容

public class YmlConfigurationSelection {

    @Autowired
    private ApplicationFactory applicationFactory;

    private ApplicationConfig applicationConfig;

    public Object accessingProperties(String application) {
        applicationConfig = applicationFactory.getApplicationPropertiesConfig(application);

        return null;
    }
}

MultipleYmlDemoProject.java的内容

@SpringBootApplication
@SpringBootConfiguration
@PropertySource(factory = ApplicationAbcConfig.class, value = "classpath:application-abc.yml")
@PropertySource(factory = ApplicationXyzConfig.class, value = "classpath:application-xyz.yml")
public class MultipleYmlDemoProject {

    public class MultipleYmlDemo {

        public static void main(String[] args) {
            ConfigurableApplicationContext ctx =
                    SpringApplication.run(YamlPropertysourceApplication.class, args);
            ConfigurableEnvironment env = ctx.getEnvironment();
        }
    }

}
java spring-boot yaml configuration-files properties-file
1个回答
0
投票

似乎您有一个试图迁移到Spring Boot的旧的Spring应用程序。

Spring boot本机可与yaml文件一起使用,因此,如果以spring boot方式进行集成,则可以删除许多必须维护的样板代码。另外,配置的命名也是有问题的:名称application-<something>.yml保留用于Spring Boot配置文件,也许如果您重命名为myprops-abc/xyz.yaml,它将以不同的方式运行,我不能肯定地说。 >

总的来说,我建议您采用以下方式,这比IMO好得多:

  1. 两个配置集都必须加载到一个配置中,因此创建一个表示该配置的配置属性文件:
  2. 
    @ConfigurationProperties(prexix="security")
    public class SecurityConfigProperties {
    
        private SecurityRealm abc;
        private SecurityRealm xyz;
    
        // getters, setters
    }
    
    public class SecurityRealm {
        private Authentication autentication;
        private Operations operations;
        // getters setters 
    }
    
    public class Authentication {...}
    private class Operations {...}
    
  1. 现在将abc和xyz yaml中的所有内容放入一个文件application.yaml,并提供一个'security'前缀:
  2. 
    security:
       abc:   // note, this 'abc' matches the field name of the configuration
         authentication: 
            ...
         operations:
            ....
       xyz:
         authentication: 
            ...
         operations:
            ....
    
  1. 确定,所有内容都已映射,请按以下方式创建配置:
  2. @Configuration
    @EnableConfigurationProperties(SecurityConfigProperties.class)
    public class SecurityConfiguration {
    
        @Bean
        public SecurityBeanForABC(SecurityConfigProperties config) {
          return new SecurityBeanForABC(config.getAbc().getAuthentication(), config.getAbc().getOperations());
        } 
    
        ... the same for XYZ
    }
    
    

注意,使用这种方法,您仅在java对象中维护配置映射,并且没有用于加载/解析属性的代码)-一切都由spring boot自动完成。如果配置特殊的注释处理器并具有下降的IDE,您甚至可以为这些yaml属性获得自动完成功能,但此问题超出了范围。关键是,以Spring Boot直接支持的方式进行操作有很多优点:)

© www.soinside.com 2019 - 2024. All rights reserved.