【问题标题】:How to load properties in Spring Boot Library Project with environments?如何使用环境在 Spring Boot 库项目中加载属性?
【发布时间】:2023-02-22 05:33:14
【问题描述】:

我有一个Spring Boot 安全库项目作为包/依赖项。现在我想为不同的环境添加属性[local,dev,stage,prod],所以我在resources目录中添加了文件security-properties.yml,如下所示

security:
  jwt:
    secret: xxxxxxxxxxxxxxxxxxxx

---

spring:
  profiles: local

security:
  # Proxy
  proxy:
    authUrl: http://localhost:8080
  # JWT
  jwt:
    expiryMs: 14400000


---

spring:
  profiles: dev

security:
  # Proxy
  proxy:
    authUrl: https://example-dev.com
  # JWT
  jwt:
    expiryMs: 43200000


---

spring:
  profiles: stage

security:
  # Proxy
  proxy:
    authUrl: https://example-stage.com
  # JWT
  jwt:
    expiryMs: 43200000


---

spring:
  profiles: prod

security:
  # Proxy
  proxy:
    authUrl: https://example.com
  # JWT
  jwt:
    expiryMs: 43200000

现在加载我创建的属性SecurityProperties.class

@Getter
@Setter
@Configuration
@PropertySource(value = "classpath:security-properties.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {

    private Jwt jwt = new Jwt();

    private Proxy proxy = new Proxy();

    @Getter
    @Setter
    public static class Jwt {

        private String tokenHeader = "Authorization";

        private String tokenHead = "Bearer ";

        private String secret;

        private Long expiryMs = 43200000L;
    }

    @Getter
    @Setter
    public static class Proxy {

        private String authUrl;
    }

    @Getter
    @Setter
    public static class IgnoreUrls {

        private String[] get = {};

        private String[] post = {};

        private String[] patch = {};

        private String[] delete = {};
    }
}

YamlPropertySourceFactory.class加载yaml文件

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(resource.getResource());
        yamlFactory.afterPropertiesSet();
        Properties properties = yamlFactory.getObject();
        assert properties != null;
        return new PropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties);
    }
}

现在,在为库项目发布工件并在主项目中注入依赖项后,我无法从库项目加载环境的安全属性。

笔记:我可以在主项目的application-{profile}.yml 文件中添加安全属性,它有效

如何在 Spring Boot Library 项目 [dependency] 中添加属性?

【问题讨论】:

    标签: spring-boot spring-security yaml


    【解决方案1】:

    再会。

    该主题的任何答案或解决方案?

    【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2021-02-09
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2018-03-28
    • 2021-11-22
    相关资源
    最近更新 更多