Search code examples
springspring-bootconfigurationspring-data-jpadatasource

Spring Boot external DataSource bean


I am trying to create a common library that includes several stuff needed by my microservices. One of those things is the ACL functionality provided with spring-security. My initial thought was to initialize all ACL-related beans from a @Configuration file in the common library and each time a microservice needs this functionality i could use the @Import annotation(to my microservice project) to "enable" it.

Some of these beans require the famous javax.sql.DataSource to work, so in my common library i autowired it as follows:

@Configuration
public class AclConfiguration {

@Autowired
DataSource dataSource 

When i decide that i want this configuration to take place i go to my microservice project (let's say RulesApplication) and on the main class (annotated with @SpringBootApplication) i do the following

@SpringBootApplication
@EnableJpaRepositories
@EnableJpaAuditing
@EnableCaching
@Import(AclConfiguration.class)
public class RulesApplication {

.
.
.

The problem is that the DataSource bean cannot be seen from the common library, although it is being created as expected (validated just by removing the @Import).

Everytime i import the configuration from the common library i get a :

Caused by: java.lang.IllegalArgumentException: DataSource required
    at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.5.RELEASE.jar:5.2.5.RELEASE]

Indicating that the DataSource bean is null.

What am i missing here?


Solution

  • Coming up from some digging.. There was never a real problem with the DataSource bean. All the frustration was created by double-defining another Bean in the same class, which led to all the @Autowired beans failure to initialize.

    As a result from this research(as other posts mentioned) the bean initialization is working smoothly between shared projects, so most of the times this error will occur from double-defining/badly-defining other beans.