简体   繁体   中英

I need to invoke a Spring Service from a java class, how to set the active profile for spring application from java class

*I need to invoke a spring service from my java class, how would i set the active profile dynamically for spring service. here's the code

java code
public void abc() {
AccountDetailService service = new AccountDetailService();
service.getAccountDetails();
}
AccountDetailService
@Profile
@Log
@Component
private void getAccountDetails() {

      String filename=environment.getProperty("fileName");
      accountDaoImpl.getDetails(filename);
}

i have various profiles like dev,qa and prod how would i pass active profiles from my java class when invoking spring service.*

You don't need to pass any profiles to your service. Simply, create configurations for different profiles. These configurations will provide the correct service instance for given profile. Here you have an example of such configuration class:

@Configuration
@Profile(value = "test")
public class ServiceTestConfig
{
    @Bean 
    public Service service()
    {
        return new TestService();
    }
}

Create another configuration with other @Profile annotation and Spring will automatically create proper instances. You can set active profile in many ways, the simplest is to change the spring.profiles.active property in your application.properties . Refer to Spring documentation to learn more about profiles:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

Update

If you really need to pass your active profile to your service in runtime, you can inject Environment instance and call getActiveProfiles() . See the javadoc: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/Environment.html . Just keep in mind it's not the way profiles should be used in Spring. The example I provided before is considered the best practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM