Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Profile in spring boot

I have spring boot application (1.1.5.RELEASE) and enabling my profiles via the configuration protperty spring.profiles.active=MyProfile

The profile gets activated correctly which I can see by beans from that profile being created.

Then I have a @Controller used as follows:

@Controller
@RequestMapping("/someUrl")
@Profile("MyProfile")
public class MyController {
...
}

This controller is not instantiated and URL used in the controller are not mapped. In the same package I have another controllers which are not limited by @Profile and these get instsantiated and mapped as expected.

So is using @Profile annotation on controller something which is not compatible with spring boot? Is there other approach I should be using?

Edit: It seems to be a bug after all as if I include -Dspring.profiles.active=MyProfile as JVM property the controller gets instantiated :'(

Edit2: So here comes the interesting part:

  • If you define spring.profiles.active in application.properties which is loaded by default from classpath thne it works

  • when you rename the file to test.properties and include it via @PropertySource("classpath:test.properties") it stops working. Will raise a bug against it.

Edit 3: As promised: https://github.com/spring-projects/spring-boot/issues/1417

Thanks!

like image 494
Jan Zyka Avatar asked Aug 21 '14 13:08

Jan Zyka


People also ask

How do I set environment specific properties in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.

Can you use @component together with profile?

Yes, @Profile annotation can be used together with @Component on top of the class representing spring bean.


2 Answers

I've tracked this down to what I believe to be a bug in Spring. See SPR-12111 for more details.

like image 93
Andy Wilkinson Avatar answered Sep 23 '22 20:09

Andy Wilkinson


You can definitely annotate a controller with @Profile in Spring Boot, just as you are doing above. MyController gets instantiated if MyProfile is active. Are you sure that "MyProfile" is the active profile? Are you setting the spring.profiles property?

http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/context/annotation/Profile.html The @Profile annotation may be used in any of the following ways:

as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes as a meta-annotation, for the purpose of composing custom stereotype annotations

like image 42
gyoder Avatar answered Sep 23 '22 20:09

gyoder