当前位置: 首页 > 知识库问答 >
问题:

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

步博涉
2023-03-14

我在Spring Boot中的资源类路径位置中有多个yml文件,就像下面的Spring Boot结构一样。起初,我只为abc的申请而写。当时,这个文件的所有值都加载到了相应的类中,但是当我添加到另一个文件应用程序xyz时。然后,yml也会加载到相应的配置类中,但此时只加载应用程序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

申请内容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

应用程序配置的内容。JAVA

public interface ApplicationConfig {
    public Authentication getAuthentication();

    public void setAuthentication(Authentication authentication);

    public Operations getOperations();

    public void setOperations(Operations operations);
}

身份验证的内容。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;
    }
}

有效载荷的内容。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;
    }
}

请求负载的内容。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;
    }
}

责任书的内容。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;
    }
}

ApplicationABC配置的内容。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();
        }
    }

}

共有1个答案

傅经业
2023-03-14

看起来您有一个旧的spring应用程序试图迁移到spring boot。

Spring启动原生工作于yaml文件,所以如果您以Spring启动的方式进行集成,将有可能删除许多您必须维护的样板代码。配置的命名也是有问题的:名称应用程序-

总而言之,我建议你采用以下方式,在我看来,这是更好的方式:

  1. 两个配置集必须加载到一个配置中,因此创建一个表示这一配置的配置属性文件:

@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 {...}

security:
   abc:   // note, this 'abc' matches the field name of the configuration
     authentication: 
        ...
     operations:
        ....
   xyz:
     authentication: 
        ...
     operations:
        ....
@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靴直接支持的方式做事有很多好处:)

 类似资料:
  • 1-我有一个带有Spring Boot的API,我需要配置两个DBMS(MySQL和Postgres)。 2-对于每个DBMS,我需要配置不同的配置文件。(Dev,Prod) 遵循我的MySQL配置类: 我以为我的出口是: 重要: 当我将配置文件配置为连接到我的MySQL Dev数据库时,我只想连接到它。我想要同样的结果,当它是MySQL的Prod的基础时。 当我将配置文件配置为连接到我的Post

  • 多文件配置 自版本4.23.0起,v2ray程序支持使用多个配置文件。 多配置文件的主要作用在于分散不同作用模块配置,便于管理和维护。该功能主要考虑是为了丰富v2ray生态链,比如对于GUI的客户端,一般只实现节点选择等固定的功能,对于太复杂的配置难以图形化实现;只需留一个confdir的自定义配置目录供配置复杂的功能;对于服务器的部署脚本,只需往confdir添加文件即可实现配置多种协议...等

  • 我在liberty中部署了多个WebApp,它们都有自己的log4j配置文件,每个WAR中的log4j配置文件位于WAR的WEB-INF/classes文件夹中。添加log4j配置的web.xml代码片段如下: 这似乎适用于所有其他Tomcat和Jboss应用服务器,但不适用于WebSphere Liberty Profile。即使在WebSphere Basic profile中,似乎也是如此。

  • 本文向大家介绍springboot 多环境配置 yml文件版的实现方法,包括了springboot 多环境配置 yml文件版的实现方法的使用技巧和注意事项,需要的朋友参考一下 关于 dev、sit、uat、prod多环境切换的配置 最近小伙伴跟杨洋我聊到了多环境配置的问题,网上的大部分教程都是copy的,很多文章根本就没法用,小伙伴很苦恼啊,于是心(yu)地(shu)善(lin)良(feng)的杨

  • 我在Android项目中工作,我使用gitlab。 我配置了 gitlab-ci.yml 文件,我尝试提交我的Android项目,但我在 gitLab 管道中遇到了问题。 我迁移我的代码,我正在尝试构建我的应用程序,但我收到下面的错误: 失败:构建失败,出现异常。 > < li> 哪里出错:配置项目时出现问题:app。您尚未接受以下SDK组件的许可协议:[constraint layout for