1

I have a standard rest-api spring-boot application.

Controller with injected service

@RestController
@RequestMapping("/foo")
@AllArgsConstructor
public class SomeController {

    private final SomeService someService;
    
    public void someMethod(){
         someService.toDoSomething();
    }

}

and service with injected other beans

@Setter
public class SomeService {
    private AnotherVeryImportantBean anotherVeryImportantBean;
    private RestTemplateBuilder restTemplate;

    public void toDoSomething() {
         anotherVeryImportantBean.someAction();
    }

In my case, the bean AnotherVeryImportantBean is created in another dependency, which I connect to the spring-boot application. Whether to create a bean or not is decided by a variable in the application.yml file.

like this:

another.service.enabled: true

Of course I have config class for service

@Configuration
@RequiredArgsConstructor
public class SomeConfig {
    private final AnotherVeryImportantBean anotherVeryImportantBean;

    @Bean
    public SomeService someService(RestTemplateBuilder restTemplate) {
         SomeService foo = new SomeService();
         foo.setAnotherVeryImportantBean(anotherVeryImportantBean);
         foo.setRestTemplate(restTemplate);
         return foo;
    }

The problem is that this controller and service are not the only ones in the application. I would like the application not to crash completely if this particular controller and service are not formed. If the bean is not created for some reason, I just don't use that functionality (this controller).

At this point, the application crashes because AnotherService cannot be injected into someService (In case where, for some reason, it was not created).

I tried adding an annotation to config class

@ConditionalOnBean(AnotherVeryImportantBean.class)

like this:

@ConditionalOnBean(AnotherVeryImportantBean.class)
@Configuration
@RequiredArgsConstructor
public class SomeConfig {
    private AnotherVeryImportantBean anotherVeryImportantBean;

    @Bean
    public SomeService someService(RestTemplateBuilder restTemplate) {
         SomeService foo = new SomeService();
         foo.setAnotherVeryImportantBean(anotherVeryImportantBean);
         foo.setRestTemplate(restTemplate);
         return foo;
    }

But the problem is that conditional in SomeConfig checks if the bean is in the container before it is created.

How can I handle an error when a bean cannot inject another dependency into itself?

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
fckNewbee
  • 33
  • 6
  • See https://stackoverflow.com/questions/42135102/how-to-set-autowired-constructor-params-as-required-false-individually – tgdavies Oct 31 '22 at 09:11
  • Have you taken a look at `ConditionalOnProperty` ? You'd add this to all the beans that you only want present if the `another.service.enabled` property is present in your yml. – invzbl3 Oct 31 '22 at 12:03

0 Answers0