spring-boot-starter can not find beans - spring

I have a autoconfiguration class SFConfig that defines the following beans
#Bean
#ConditionalOnBean(value = SalesforceClientConfig.class)
SalesforceClient sfClient(SalesforceClientConfig sfConfig){
return SalesforceRestClient.from(sfConfig);
}
#Bean
//#ConditionalOnBean(value = Authentication.class)
SalesforceClientConfig sfClientConfig(Authentication sfAuthentication){
return DefaultSalesforceClientConfig.builder()
.authentication(sfAuthentication)
.mapper(mapper())
.build();
}
As evident sfClient bean should be created because SalesforceClientConfig is created. But it throws an exception:
Bean method 'sfClient' in 'SFConfig' not loaded because #ConditionalOnBean (types: com.ondeck.salesforceclient.SalesforceClientConfig; SearchStrategy: all) did not find any beans
This weird because this is an autoconfiguration class and it should find that bean. Any thoughts?
Here is how I have defined my autoconfiguration classes in the file:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ondeck.letter.config.SpringJpaDBConfig,\
com.ondeck.letter.config.SFConfig

According to Annotation Type ConditionalOnBean, it's recommended to use #ConditionalOnBean annotation in the auto configuration classes annotated with #EnableAutoConfiguration.
So probably you have not properly defined auto configuration class.

Related

#ConditionalOnBean not work for spring boot test

Hy everyone! I'm trying to solve the problem for a very long time.
There is very simple spring boot test
public class ApplicationTest {
#Test
void testContext() {
SpringApplication.run(Application.class);
}
}
And several beans...
#Service
#ConditionalOnBean(CommonService.class)
#RequiredArgsConstructor
public class SimpleHelper {
...
#Service
#RequiredArgsConstructor
#ConditionalOnBean(CommonFeignClient.class)
public class CommonService {
...
#FeignClient(
name = "CommonClient",
url = "localhost:8080"
)
public interface CommonFeignClient {
And the main class look as
#SpringBootApplication
#EnableFeignClients(clients = AnotherFeignClient.class)
public class Application {
When the spring application starts everything works ok. SimpleHelper does not created.
But in the spring boot test throw the exception:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'simpleHelper' defined in URL [...]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'foo.bar.CommonService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Please help, I don't understand what's going on anymore =)
Spring boot version is 2.3.0.RELEASE.
To use #ConditionalOnBean correctly, CommonService needs to be an auto-configuration class or defined as a bean by an auto-configured class rather than a service that's found by component scanning. This ensures that the bean on which CommonService is conditional has been defined before the condition is evaluated. The need for this is described in the annotation's javadoc:
The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

Spring autoconfigurations, #ConditionalOnBean with a #Repository

I have a starter module which expose a marker interface along with some repository:
interface AwesomeRepo
...
internal interface FakeRepository: Repository<JPAStub, String>, AwesomeRepo {
fun count(): Long
}
#Entity
class JPAStub(#Id val name: String)
#Configuration(proxyBeanMethods = false)
#ConditionalOnBean(EntityManagerFactory::class)
#AutoConfigureAfter(JpaRepositoriesAutoConfiguration::class)
#EnableJpaRepositories(basePackageClasses = [FakeRepository::class])
#EntityScan(basePackageClasses = [FakeRepository::class])
class AwesomePersistenceAutoConfiguration
In another module, I have an auto configuration which depends on the AwesomeRepo to instantiate the AwesomeApplicationService
#Configuration(proxyBeanMethods = false)
class AwesomeAutoConfiguration {
#Bean
#ConditionalOnMissingBean
#ConditionalOnBean(AwesomeRepo::class)
fun awesomeAppService(awesomeRepo: AwesomeRepo) =
AwesomeApplicationService(awesomeRepo)
I import both autoconfigure starters in a root project.
I observe:
AwesomeApplicationService cannot be instantiated because AwesomeRepo bean cannot be found
When enabling debug through debug=true:
AwesomeAutoConfiguration #awesomeAppService:
Did not match:
- #ConditionalOnBean (types: *****.AwesomeRepo; SearchStrategy: all) did not find any beans of type *******.AwesomeRepo(OnBeanCondition)
I tried adding #AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) to AwesomePersistenceAutoConfiguration and #AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) to AwesomeAutoConfiguration. It did not change the issue
When I remove the #ConditionOnBean(AwesomeRepo::class), the AwesomeApplicationService is correctly instantiated with the repository and everything is fine.
Why does the #ConditionOnBean(AwesomeRepo::class) does not detect the AwesomeRepo bean?
EDIT: After more trials and errors, it seems order was causing the issue, applying accepted answer worked. If someone needs to go further there is a baseline of code illustrating the issue here: https://github.com/Nimamoh/spring-autoconfigurations-conditionalonbean-with-a-repository (accepted answer is on snic-answer branch)
AwesomeAutoConfiguration should be ordered after AwesomePersistenceAutoConfiguration so that the bean definitions for the repositories are processed before the condition kicks in.
There is a note in #ConditionalOnBean about this specifically:
The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.
You can use #AutoConfigureAfter(AwesomePersistenceAutoConfiguration.class) on AwesomeAutoConfiguration to order things properly.

Spring Websocket TaskExecutor-beans displaces "applicationTaskExecutor"-bean

I have a Spring Boot 2.1.8 Application that uses #Async-Tasks. All #Async-Tasks used to be executed by an automatically configured ThreadPoolTaskExecutor-bean named applicationTaskExecutor.
What did I change?
With spring-boot-starter-websocket in the class path and a #EnableWebSocketMessageBroker configuration the applicationTaskExecutor-bean is gone and replaced by four beans with the names
clientInboundChannelExecutor,
clientOutboundChannelExecutor,
brokerChannelExecutor,
and messageBrokerTaskScheduler.
Spring logs to the console: AnnotationAsyncExecutionInterceptor : More than one TaskExecutor bean found within the context, and none is named 'taskExecutor'. Mark one of them as primary or name it 'taskExecutor' (possibly as an alias) in order to use it for async processing: [clientInboundChannelExecutor, clientOutboundChannelExecutor, brokerChannelExecutor, messageBrokerTaskScheduler]
#Async-tasks are now executed by SimpleAsyncTaskExecutor.
Question
Why can't all beans co-exist? Why won't Spring create a applicationTaskExecutor-bean when spring-websockets is configured?
As #M. Deinum mentioned in the comments a #ConditionalOnMissingBean in TaskExecutionAutoConfiguration.java [0] results in the described behavior
I solved it by creating the bean by myself.
#ConditionalOnClass(ThreadPoolTaskExecutor.class)
#Configuration
public class ApplicationTaskExecutorBeanConfig {
#Lazy
#Bean(name = {APPLICATION_TASK_EXECUTOR_BEAN_NAME, DEFAULT_TASK_EXECUTOR_BEAN_NAME})
public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
return builder.build();
}
}
First I tried to prefer the bean from TaskExecutionAutoConfiguration.java by annotating my bean factory method with
#ConditionalOnMissingBean(name = {APPLICATION_TASK_EXECUTOR_BEAN_NAME, DEFAULT_TASK_EXECUTOR_BEAN_NAME})
but it didn't worked because my bean factory method gets invoked earlier than the one in TaskExecutionAutoConfiguration.java.
[0] https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfiguration.java#L78
Thanks to #M. Deinum for your comment.

Including Spring Data breaks auto serialization in Spring Boot application

I recently added Spring-data to my project and then I found that in my REST controllers, my models provided by clients were no longer being automatically serialized from JSON. How can I fix this?
I added:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
and now the User param isn't having it's String arg constructor called and u is null!
#PostMapping()
#ResponseBody
public User createUser(HttpServletRequest request, #RequestParam("user") User u) {
log.info("Got user! " + u);
users.save(u);
Optional<User> found = users.findById(u.getEmail());
log.info("Saved user!! ");
return found.get();
}
If you build your .war with spring-data, run java -jar <path-to-war> --debug and then build it/run it without spring-data and diff the outputs, you can see that the following beans are included when spring-data is added.
SpringDataWebAutoConfiguration matched:
- #ConditionalOnClass found required classes 'org.springframework.data.web.PageableHandlerMethodArgumentResolver', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition)
- found ConfigurableWebEnvironment (OnWebApplicationCondition)
- #ConditionalOnMissingBean (types: org.springframework.data.web.PageableHandlerMethodArgumentResolver; SearchStrategy: all) did not find any beans (OnBeanCondition)
SpringDataWebAutoConfiguration#pageableCustomizer matched:
- #ConditionalOnMissingBean (types: org.springframework.data.web.config.PageableHandlerMethodArgumentResolverCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)
SpringDataWebAutoConfiguration#sortCustomizer matched:
- #ConditionalOnMissingBean (types: org.springframework.data.web.config.SortHandlerMethodArgumentResolverCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)
This is because Spring data exposes REST controllers that link to your data repositories as mentioned here: http://spring.io/projects/spring-data-rest and this breaks the default auto-configurations for serializing objects passed to REST controllers.
Simply exclude the auto configuration and your existing auto serialization will work:
#SpringBootApplication(exclude = { SpringDataWebAutoConfiguration.class })
public class MyApplication{
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

Custom Auto Configuration in Spring Boot cannot find DataSource with ConditionalOnBean

I have a problem with Spring Boot version 2.0.1.RELEASE (in Spring Boot 2.0.0.RELEASE the below configuration worked nice).
Could somebody help me out please why this configuration is not working?
I have this configuration and this config did not match the ConditionalOnBean condition.
The AutoConfigureOrder / Order / AutoConfigureAfter seems that doesn't have any effect.
#Configuration
#ConditionalOnClass({DataSource.class, JpaRepository.class})
#ConditionalOnBean(DataSource.class)
#AutoConfigureAfter(DataSourceAutoConfiguration.class)
#ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureOrder(LOWEST_PRECEDENCE)
#Order(LOWEST_PRECEDENCE)
public class MyJpaAuditAutoConfiguration {
#ConditionalOnMissingBean
#Bean
public MyTransactionHelper transactionHelper() {
return new MyTransactionHelper();
}
}
In spring.factories I have:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.MyJpaAuditAutoConfiguration
Application start output for this configuration:
DataSourceAutoConfiguration matched:
- #ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'; #ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
...
JpaAuditAutoConfiguration:
Did not match:
- #ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans of type javax.sql.DataSource (OnBeanCondition)
Matched:
- #ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.data.jpa.repository.JpaRepository'; #ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- #ConditionalOnProperty (spring.data.jpa.repositories.enabled=true) matched (OnPropertyCondition)
In my opinion, the config class is evaluated before DataSourceAutoConfiguration and that's the reason why the bean cannot be found.
Other configs like DataSourceHealthIndicatorAutoConfiguration found the bean.
DataSourceHealthIndicatorAutoConfiguration matched:
- #ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource'; #ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- #ConditionalOnEnabledHealthIndicator management.health.defaults.enabled is considered true (OnEnabledHealthIndicatorCondition)
- #ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found bean 'dataSource' (OnBeanCondition)
After spring boot upgrade to version 2.1.2.RELEASE it was solved automatically.
(I renamed some classes in the answer)
So in Spring Boot version 2.1.2.RELEASE:
#Configuration
#ConditionalOnBean(DataSource.class)
#ConditionalOnClass({DataSource.class, JpaRepository.class})
#ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class JpaTransactionHelperAutoConfiguration {
#ConditionalOnMissingBean
#Bean
public TransactionHelper transactionHelper() {
return new TransactionHelper();
}
}
NOTE: by removing the #AutoConfigureAfter(DataSourceAutoConfiguration.class) it won't work in Spring Boot version 2.1.2.RELEASE.
In Spring Boot version 2.0.1.RELEASE I just removed the ConditionalOnBean annotation:
#Configuration
#ConditionalOnClass({DataSource.class, JpaRepository.class})
#ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class JpaTransactionHelperAutoConfiguration {
#ConditionalOnMissingBean
#Bean
public TransactionHelper transactionHelper() {
return new TransactionHelper();
}
}

Resources