Spring Boot doesn't allow Optional Bean to be Lazy when running tests

Viewed 871

In my Spring Boot 2.1 application, I have a service class that looks something like this:

@Service
public class AImpl implements A {
    @Autowired
    B bservice;
}

And then the autowired service B looks like this:

@Service
public class BImpl implements B {
    @Autowired(required = false)
    @Lazy
    org.springframework.web.client.RestOperations restTemplate;
}

And in my test class:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {...})
@DataJpaTest
@EnableJpaRepositories("com.xxx")
@EntityScan("com.xxx")
public class CImplTest {
    @Autowired
    B bservice;
    @Autowired
    A aservice;
}

When running my tests, I get the following error message:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestOperations' available: Optional dependency not present for lazy injection point

However when running the application, I don't face this issue and it runs fine.

NOTE: I have tried replacing the rstTemplate Autowiring with Java 8 Optional and it doesn't work well.

1 Answers

Not sure if this is the exact solution to this problem but when tried with Java 8 optional type, this didn't work out. However, when I switched to Spring's ObjectProvider, it is working fine. Ideally, this is just a workaround and not the root cause for this issue.

Related