How do you get current active/default Environment profile programmatically in Spring?

前端 未结 6 872
梦毁少年i
梦毁少年i 2020-11-29 19:17

I need to code different logic based on different current Environment profile. How can you get the current active and default profiles from Spring?

6条回答
  •  清酒与你
    2020-11-29 20:22

    Extending User1648825's nice simple answer (I can't comment and my edit was rejected):

    @Value("${spring.profiles.active}")
    private String activeProfile;
    

    This may throw an IllegalArgumentException if no profiles are set (I get a null value). This may be a Good Thing if you need it to be set; if not use the 'default' syntax for @Value, ie:

    @Value("${spring.profiles.active:Unknown}")
    private String activeProfile;
    

    ...activeProfile now contains 'Unknown' if spring.profiles.active could not be resolved

提交回复
热议问题