什么是 Spring 的 `@Profile` 注释的等价物?

What is the equivalent of Spring's `@Profile` annotation for microprofile?

我习惯于使用 Spring 并大量使用 @Profile 用于 local/dev/production 环境的不同配置。我们已经转向 microprofile - 是否有一种等效的简单方法可以在运行时使用 microprofile 指定不同的配置?

您可以使用 Environment with @Requires / @Requirements ,简单示例 env = "foo":

Application.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.java 对于 foo 环境:

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.java 对于 bar 环境:

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");
    }

}

application-foo.yml foo env

的属性
some:
  property: some-property-foo

application-bar.yml bar env

的属性
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

看看Cloud Configuration with already defined Environment

P.S。对于 IntelliJ IDEA(Run/Debug 配置)还设置首选 环境变量 MICRONAUT_ENVIRONMENTS=bar