1

我习惯使用 Spring,并且大量用于@Profile本地/开发/生产环境的不同配置。我们已经转移到 microprofile - 是否有一种等效的简单方法可以在运行时使用 microprofile 指定不同的配置?

4

1 回答 1

2

您可以将Environment@Requires / @Requirements一起使用,简单示例env = "foo"

应用程序.java

package helloworld;

import io.micronaut.context.ApplicationContext;
import io.micronaut.runtime.Micronaut;

public class Application {

    public static void main(String[] args) {
        ApplicationContext context = Micronaut.run(Application.class);
        SomeService someService = context.getBean(SomeService.class);

        someService.doWork();
        Optional<String> someProperty = context.getProperty("some.property", String.class);
        System.out.println("some.property=" + someProperty.get());
    }

}

SomeService.java

package helloworld;

public interface SomeService {

    void doWork();

}

用于环境的SomeServiceFoo.javafoo

package helloworld;

import io.micronaut.context.annotation.Requires;

import javax.inject.Singleton;

@Singleton
@Requires(env = "foo")
public class SomeServiceFoo implements SomeService {

    @Override
    public void doWork() {
        System.out.println("SomeServiceFoo work");
    }

}

用于环境的SomeServiceBar.javabar

package helloworld;

import io.micronaut.context.annotation.Requires;

import javax.inject.Singleton;

@Singleton
@Requires(env = "bar")
public class SomeServiceBar implements SomeService {

    @Override
    public void doWork() {
        System.out.println("SomeServiceBar work");
    }

}

fooenv的 application-foo.yml属性

some:
  property: some-property-foo

barenv的 application-bar.yml属性

some:
  property: some-property-bar

运行应用程序:

java -Dmicronaut.environments=foo -jar helloworld-0.1.jar

应用程序输出:

SomeServiceFoo work
some.property=some-property-foo

您还可以设置环境变量MICRONAUT_ENVIRONMENTS=bar,bar2

并查看具有已定义环境的云配置

用于IntelliJ IDEA(运行/调试配置)的 PS还设置首选环境变量 MICRONAUT_ENVIRONMENTS=bar

于 2019-06-13T22:32:08.873 回答