Quarkus:如何仅针对非 PROD 配置文件运行 StartupEvent?

Esp*_*sso 2 quarkus

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

geo*_*and 5

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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