Default Spring bean when profile is not present

1.4k views Asked by At

I'm using Spring MVC controllers, and I'd like to make some extra request-mapped methods available during development. I can do this using Spring profiles:

@Controller
@Profile("!dev")
public class DefaultController {

}

@Controller
@Profile("dev")
public class DevController extends DefaultController {

}

But ideally, I'd rather not pollute the production classes' code with annotations referring to the 'dev' profile.

I think maybe it's possible using Primary annotation, but I can't get it to work. This post seems to say that this should work:

@Controller
public class DefaultController {

}

@Controller
@Profile("dev")
@Primary
public class DevController extends DefaultController {

}

But when I do that, Spring tries to load both controllers when it starts up under the 'dev' profile, and fails with

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0'
...
There is already 'defaultController' bean method

Is what I want to do possible? If so, how can I do it?

1

There are 1 answers

1
Nikolay Rusev On BEST ANSWER

The problem here is that your class DevController inherits from DefaultController. Keep classes separate. Don't extend DevController with DefaultController even if the contents are same.