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

Viewed 165
@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);
    }
}
1 Answers

There are a coupld of ways you can do this.

The first is to use io.quarkus.runtime.configuration.ProfileManage like so:

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

The second is to use io.quarkus.arc.profile.UnlessBuildProfile like so:

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

The second way is better since it will result in Startup never becoming a CDI bean when you build the production application.

Related