resources中的yaml文件引用pom.xml数据

在pom.xml中插入如下代码:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>
<profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <profileActive>dev</profileActive>
                <task.test>10</task.test>
            </properties>
        </profile>

        <profile>
            <id>test</id>
<!--            <activation>-->
<!--                <activeByDefault>true</activeByDefault>-->
<!--            </activation>-->
            <properties>
                <profileActive>test</profileActive>
                <task.test>11</task.test>
            </properties>
        </profile>
    </profiles>

当resources中的参数想引用的时候加上@@,比如在test.xml有如下代码:

task:
  size: @task.test@

task.size引用了pom.xml的task.test,值为10,因为 <activeByDefault>true</activeByDefault> 表示默认用 dev 这个环境。其次,

filtering:开启过滤,用指定的参数替换directory下的文件中的参数

directory:指定资源文件的位置

public class ConfigParamFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, null);
        }
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}


@Component
@ConfigurationProperties(prefix = "task")
@PropertySource(value = "classpath:test.yml", encoding = "utf-8",factory = ConfigParamFactory.class)
public class Test {

    private Integer size;

    public Test(Integer size) {
        this.size = size;
    }

    public Test() {
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }
}
@SpringBootApplicationpublic class HelloMain {
public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(HelloMain.class, args);

        Test test = run.getBean("test", Test.class);
        System.out.println(test.getSize());
    }
}

输出10,表示上述成立

posted on 2021-07-21 09:42  ustcwei  阅读(686)  评论(0)    收藏  举报