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

 ̄綄美尐妖づ 提交于 2019-12-11 16:18:40

问题


I'm used to using Spring and have heavily used @Profile for different configurations for local/dev/production environments. We've moved to microprofile - is there an equivalent easy way to specify different configurations at runtime with microprofile?


回答1:


You can use Environment with @Requires / @Requirements , simple example with 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 for foo env:

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 for bar env:

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 properties for foo env

some:
  property: some-property-foo

application-bar.yml properties for bar env

some:
  property: some-property-bar

run application:

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

application output:

SomeServiceFoo work
some.property=some-property-foo

Also you can setup Environment variables MICRONAUT_ENVIRONMENTS=bar,bar2

and take a look at Cloud Configuration with already defined Environment

P.S. for IntelliJ IDEA (Run/Debug Configurations) also setup preferred Environment variables MICRONAUT_ENVIRONMENTS=bar



来源:https://stackoverflow.com/questions/56576269/what-is-the-equivalent-of-springs-profile-annotation-for-microprofile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!