Issue
we have a controller which gets called by cron job for healthcheck purpose in our spring application
Because we are in mid of migration process, we are disabling certain spring beans for spring profile p2 which is the new platform, and only creating them for p1 which is old profile
currently if we build our application in the new platform, we receive the following exceptions:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'some.name.of.controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private [ bean that is disabled in p2 ] bean that is disabled in p2 ; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ bean that is disabled in p2 ] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
@Controller("some.name.of.controller")
@RequestMapping("/somePath")
public class someHealthCheckController {
// the SecretObject will not be available for spring profile "p2" which only gets created in profile "p1"
@Autowired
private SecretObject secretObject
I have tried extract this autowired line into a new Java class, and having the controller create an instance of the class and invoke that method, but it didn't work.
Looking for suggestions on fixing this issue, thanks !
Solution
If SecretObject does not exists in your p2
profile, the dependency is optional, so you must annotate it with @Autowired(required=false)
and check if secretObject is null (p2
profile) or not (p1
profile) before using it. Default value of required
is true
for @Autowired
.
@Controller("some.name.of.controller")
@RequestMapping("/somePath")
public class someHealthCheckController {
// the SecretObject will not be available (null) for spring profile "p2" which only gets created in profile "p1"
@Autowired(required=false)
private SecretObject secretObject
Answered By - Sébastien Helbert
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)