Search code examples
javaspring-bootjpaentitylisteners

System.getproperty("spring.profiles.active") always getting Null in JPA Entity Listeners


I am trying to get Spring active profile in JPA Entity Listener using System.getproperty("spring.profiles.active"). But it is always returning Null profile. However I have checked on server and profile is correctly configured.

I have tried to get Spring active profile using Environment but in the listener, I am unable to @Autowired Environment also.

    @PostUpdate

    public void methodInvoked afterUpdate(Example example){

    String activeProfile = System.getproperty("spring.profiles.active");  

    }

Any guidance please !


Solution

  • You should use Environment bean while injecting it as described in this answer. SpringBeanAutowiringSupport will work if you are building a web application:

    @Autowired
    private Environment env;
    
    @PostUpdate
    public void methodInvoked afterUpdate(Example example) {
      SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
      String[] activeProfile = env.getActiveProfiles();
    
    }