Quarkus:如何 运行 StartupEvent 仅用于非 PROD 配置文件?

Quarkus: How to run StartupEvent only for non-PROD profiles?

@Singleton
public class Startup {
    private static final String ADMIN_ROLES = String.join(",", Api.adminuser.role, Api.apiuser.role);

    @Inject
    UserRepo repo;
    @Transactional
    public void loadUsersForTest(@Observes StartupEvent evt) {//TODO Need to load only for non-PROD profiles
        repo.deleteAll();// reset and load all test users
        repo.addTestUserOnly(Api.adminuser.testuser, Api.adminuser.testpassword, ADMIN_ROLES);
        repo.addTestUserOnly(Api.apiuser.testuser, Api.apiuser.testpassword, Api.apiuser.role);
    }
}

有多种方法可以做到这一点。

首先是像这样使用io.quarkus.runtime.configuration.ProfileManage

@Singleton
public class Startup {
    private static final String ADMIN_ROLES = String.join(",", Api.adminuser.role, Api.apiuser.role);

    @Inject
    UserRepo repo;
    @Transactional
    public void loadUsersForTest(@Observes StartupEvent evt) {
        if ("prod".equals(io.quarkus.runtime.configuration.ProfileManager.getActiveProfile())) { 
           return; 
        }
        repo.deleteAll();// reset and load all test users
        repo.addTestUserOnly(Api.adminuser.testuser, Api.adminuser.testpassword, ADMIN_ROLES);
        repo.addTestUserOnly(Api.apiuser.testuser, Api.apiuser.testpassword, Api.apiuser.role);
    }
}

第二种是像这样使用io.quarkus.arc.profile.UnlessBuildProfile

@UnlessBuildProfile("prod")
@Singleton
public class Startup {
    private static final String ADMIN_ROLES = String.join(",", Api.adminuser.role, Api.apiuser.role);

    @Inject
    UserRepo repo;
    @Transactional
    public void loadUsersForTest(@Observes StartupEvent evt) {
        repo.deleteAll();// reset and load all test users
        repo.addTestUserOnly(Api.adminuser.testuser, Api.adminuser.testpassword, ADMIN_ROLES);
        repo.addTestUserOnly(Api.apiuser.testuser, Api.apiuser.testpassword, Api.apiuser.role);
    }
}

第二种方法更好,因为它会导致 Startup 在构建生产应用程序时永远不会成为 CDI bean。