Disable all Database related auto configuration in Spring Boot - spring

I am using Spring Boot to develop two applications, one serves as the server and other one is a client app. However, both of them are the same app that function differently based on the active profile. I am using auto configuration feature of Spring Boot to configure my applications.
I want to disable all the database related auto configuration on client app, since it won't be requiring database connection. Application should not try to establish connection with the database, nor try to use any of the Spring Data or Hibernate features. The enabling or disabling of the database auto configuration should be conditional and based on the active profile of the app.
Can I achieve this by creating two different application.properties files for respective profiles?
I tried adding this to my properties file,
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
But, the application still tries to connect to the database on start. Are those exclusions sufficient for achieving my requirement?

The way I would do similar thing is:
#Configuration
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#Profile ("client_app_profile_name")
public class ClientAppConfiguration {
//it can be left blank
}
Write similar one for the server app (without excludes).
Last step is to disable Auto Configuration from main spring boot class:
#SpringBootApplication
public class SomeApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SomeApplication.class);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SomeApplication.class);
}
}
Change: #SpringBootApplication into:
#Configuration
#ComponentScan
This should do the job. Now, the dependencies that I excluded in the example might be incomplete. They were enough for me, but im not sure if its all to completely disable database related libraries. Check the list below to be sure:
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#auto-configuration-classes

For disabling all the database related autoconfiguration and exit from:
Cannot determine embedded database driver class for database type NONE
1. Using annotation:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(PayPalApplication.class, args);
}
}
2. Using Application.properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

Seems like you just forgot the comma to separate the classes. So based on your configuration the following will work:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
Alternatively you could also define it as follow:
spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
spring.autoconfigure.exclude[1]=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.autoconfigure.exclude[2]=org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
spring.autoconfigure.exclude[3]=org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration

There's a way to exclude specific auto-configuration classes using #SpringBootApplication annotation.
#Import(MyPersistenceConfiguration.class)
#SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
#SpringBootApplication#exclude attribute is an alias for #EnableAutoConfiguration#exclude attribute and I find it rather handy and useful.
I added #Import(MyPersistenceConfiguration.class) to the example to demonstrate how you can apply your custom database configuration.

Way out for me was to add
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
annotation to class running Spring boot (marked with `#SpringBootApplication).
Finally, it looks like:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

If using application.yml:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
- org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
- org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration

Another way to control it via Profiles is this:
// note: no #SpringApplication annotation here
#Import(DatabaseConfig.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Configuration
#Import({DatabaseConfig.WithDB.class, DatabaseConfig.WithoutDB.class})
public class DatabaseConfig {
#Profile("!db")
#EnableAutoConfiguration(
exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
static class WithoutDB {
}
#Profile("db")
#EnableAutoConfiguration
static class WithDB {
}
}

I had the same problem here, solved like this:
Just add another application-{yourprofile}.yml where "yourprofile" could be "client".
In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.
In this file I put:
spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration
this should work with properties files as well.
I like the fact that there is no need to change the application code to do that.

I add in myApp.java, after #SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
And changed
#SpringBootApplication => #Configuration
So, I have this in my main class (myApp.java)
package br.com.company.project.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SomeApplication {
public static void main(String[] args) {
SpringApplication.run(SomeApplication.class, args);
}
}
And work for me! =)

In my case the spring-boot-starter-jpa dependency was being loaded from other dependency. I did this to disable the DataSource:
Check the dependency tree with mvn dependency:tree
[INFO] com.backend.app:crud-manager:jar:0.1-SNAPSHOT
[INFO] +- ...
[INFO] \- com.backend.app:crud-libraries:jar:0.1-SNAPSHOT:compile
[INFO] +- org.springframework.boot:spring-boot-starter.data-jpa:jar:2.1.6.RELEASE:compile
[INFO] +- ....
There was a sub-dependency. Add an exclusion
<dependency>
<groupId>com.backend.app</groupId>
<artifactId>crud-libraries</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusion>
</exclusions>
</dependency>
Exclude DataSourceAutoConfiguration.class in the Application file
import org.springframework.boot.autoconfigure.jdbc. DataSourceAutoConfiguration;
// add exclude
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class ...
Ensure there is no spring-boot-starter-jpa in pom.xml
** Apart, in case you also need to make it work with spring-boot-starter-batch
In the BatchConfig file:
// add extends DefaultBatchConfig
public class BatchConfig extends DefaultBatchConfig {
//add override
#Override
public void setDataSource(DataSource dataSource) {}

I was getting this error even if I did all the solutions mentioned above.
by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfig ...
At some point when i look up the POM there was this dependency in it
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
And the Pojo class had the following imports
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
Which clearly shows the application was expecting a datasource.
What I did was I removed the JPA dependency from pom and replaced the imports for the pojo with the following once
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
Finally I got SUCCESSFUL build. Check it out you might have run into the same problem

Also if you use Spring Actuator org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration might be initializing DataSource as well.

By default in Spring, all the defined beans, and their dependencies, are created when the application context is created.
In contrast, when we configure a bean with lazy initialization, the bean will only be created, and its dependencies injected, once they're needed.
spring:
main:
lazy-initialization: true
jpa:
properties:
hibernate: # lazy-initialization works with this dialect property to avoid run issues if DB is Down
dialect: org.hibernate.dialect.Oracle10gDialect

Related

Spring Boot - How to exclude one component during scan?

I have a JAR dependency that I am required to use. There is one component in that JAR that is interfering with a part of my Spring Boot application. I need to exclude that ONE component, and changing the component definition in the JAR dependency is not currently possible.
I have tried the following, but it does not work, the bean is still loaded:
#SpringBootApplication
#ComponentScan(useDefaultFilters = false, excludeFilters = [Filter(type = FilterType.ASSIGNABLE_TYPE, classes = [SomeBean::class])])
The bean is defined as:
#RestController
class SomeBean {
NOTE: These snippets are in Kotlin.
Try this
#SpringBootApplication(exclude = { SomeBean.class })
Can you do something like below to skip creating bean?
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;
#Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {}
#Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
registry.removeBeanDefinition("myBeanName");
}
}
Doesn't the #Bean/#Component/etc. or #Configuration have any Conditional annotation on it (e.g.: #ConditionalOnMissingBean, #ConditionalOnProperty, etc.)? That would be the right solution for this problem. Can you ask the maintainer to add proper conditions? So that you (and other users) don't need to hack this around.
There is a terrible hack though: BeanDefinitionRegistry#removeBeanDefinition

Spring Boot AOP in multi module project does not execute Before Advice

I'm doing my fist steps with Springs AOP and wanted to start with a simple logging advice. My project is a multi module maven project with the following structure:
parentProject
|__aop
|__data
|__web
The web module has a user service class in the package de.my.awsome.project.web.service with a saveNewUser Method:
#Service
public class UserService {
...
public MdUser saveNewUser(UserModel user) {
MdUser newUser = this.save(user);
createGroupMembership(user, newUser);
return newUser;
}
}
The method works as expected so don't bother with details about that.
What I've done now is to create the following class in the aop module:
#Component
#Aspect
public class LoggingAspect {
Logger logger = Logger.getLogger(getClass());
#Before("execution(public * de.my.awsome.project.web.service.UserService.saveNewUser(..))")
public void newUserLog(JoinPoint joinpoint) {
logger.info(joinpoint.getSignature() + " with user " + joinpoint.getArgs()[0]);
}
}
I added a dependency for the web module in the pom of the aop module:
<dependency>
<groupId>de.my.awsome.project</groupId>
<artifactId>web</artifactId>
<version>${project.version}</version>
</dependency>
I even wrote a ConfigurationClasse even though I thought this would not be necessary with SpringBoot:
#Configuration
#ComponentScan(basePackages="de.fraport.bvd.mobisl.aop")
public class AspectsConfig {
}
The expected result is a log-message like "saveNewUser with user xyz". But the logging method is never called. What have I missed to do?
#Configuration - Indicates that this file contains Spring Bean Configuration for an Aspect.
Replace #Component with #Configuration for LoggingAspect.
Well, the answer that #sankar posted didn't work either but I found the solution by myself.
I had to add a dependency to my aop module in the web modules pom, not vice versa. Then I added an Import of my AspectsConfig to the web modules SpringBootApplication class and it worked.
#SpringBootApplication
#Import(value= {JPAConfig.class, AspectsConfig.class})
#EnableAspectJAutoProxy
public class WebApplication {
#Autowired
private JPAConfig config;
#Autowired
private AspectsConfig aspectConfig;
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
The following steps work for me - see below if anyone is looking for a solution
add the aop dependency in to the main parent pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
add your Aspect implementation in he aop-sub-module
#Aspect
#Component
public class SampleAspect {
#After("execution(* de.my.awsome.project.testMethod())")
public void logAuditActivity(JoinPoint jp) {
System.out.println("TESTING ****************");
System.out.println("The method is called");
}
In your other submodule (web-submodule) add the dependancy of the aspect-submodule
<dependency>
<groupId>de.my.awsome.project</groupId>
<artifactId>aop</artifactId>
</dependency>
In your web Project include the aop package for component scan
eg. if SampleAspect is under a package de.my.awsome.project you will need to add in as follow
#ComponentScan(basePackages = {"de.my.awsome.project", "de.my.awsome.aop" }
clean build and run the app

Spring does not load data beans (#Repository) from dependency [duplicate]

I have a myapp parent pom type maven project with myapp-core and myapp-web modules. myapp-core module is added as dependency to myapp-web.
All the classes in myapp-core module reside in root package com.myapp.core and all classes in myapp-web module reside in root package com.myapp.web
The main Application.java is also in com.myapp.web package. As my core module root package is different I am including common base package "com.myapp" for ComponentScan as follows:
#Configuration
#ComponentScan(basePackages="com.myapp")
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Now the surprising thing is if I run this app using Run As -> Spring Boot App it is working fine. But if I run it as Run As -> Java Application it is failing with error saying it can't found beans defined in myapp-core module.
If I move my Application.java to com.myapp package it is working fine.
It should work even if i run it as Java Application also, right?
After enabling debug log level for spring and going through extensive logs I found that scanning for various components like JPA Repositories, JPA Entities etc are depending on the Application.java's package name.
If the JPA Repositories or Entities are not in sub packages of Application.java's package then we need to specify them explicitly as follows:
#Configuration
#ComponentScan(basePackages="com.sivalabs.jcart")
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages="com.sivalabs.jcart")
#EntityScan(basePackages="com.sivalabs.jcart")
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
With the above additional #EnableJpaRepositories, #EntityScan I am able to run it using Run As -> Java Application.
But still not sure how it is working fine when Run As -> Spring Boot App!!
Anyway I think it is better to move my Application.java to com.myapp package rather than fighting with SpringBoot!
I have the same problem. Only adding the #EnableJpaRepositories annotation can solve the issue. I tried to define basePackages in #SpringBootApplication, to no avail.
I think the package of the Application class is fed to the scanning process of JpaRepositories, but other packages defined in #SpringBootApplication are ignored.
It looks like a bug/improvement of Spring Boot.
I had a similar issue with Redis repositories that was fixed in a similar way:
#Configuration
#EnableConfigurationProperties({RedisProperties.class})
#RequiredArgsConstructor
#EnableRedisRepositories(basePackages = {"com.example.another"})
public class RedisConfig {
private final RedisConnectionFactory redisConnectionFactory;
#Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
template.setConnectionFactory(redisConnectionFactory);
template.afterPropertiesSet();
return template;
}
}

How to autowire #ConfigurationProperties into #Configuration?

I have a properties class defined like this:
#Validated
#ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
...
}
And a configuration class like this:
#Configuration
#EnableScheduling
public class HttpClientConfiguration {
private final HttpClientProperties httpClientProperties;
#Autowired
public HttpClientConfiguration(HttpClientProperties httpClientProperties) {
this.httpClientProperties = httpClientProperties;
}
...
}
When starting my spring boot application, I'm getting
Parameter 0 of constructor in x.y.z.config.HttpClientConfiguration required a bean of type 'x.y.z.config.HttpClientProperties' that could not be found.
Is this not a valid use case, or do I have to declare the dependencies some how?
This is a valid use case, however, your HttpClientProperties are not picked up because they're not scanned by the component scanner. You could annotate your HttpClientProperties with #Component:
#Validated
#Component
#ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
// ...
}
Another way of doing so (as mentioned by Stephane Nicoll) is by using the #EnableConfigurationProperties() annotation on a Spring configuration class, for example:
#EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way
#EnableScheduling
public class HttpClientConfiguration {
// ...
}
This is also described in the Spring boot docs.
In Spring Boot 2.2.1+, add the #ConfigurationPropertiesScan annotation to the application. (Note that this was enabled by default in version 2.2.0.) This will allow all classes annotated with #ConfigurationProperties to be picked up without using #EnableConfigurationProperties or #Component.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
#SpringBootApplication
#ConfigurationPropertiesScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also, to generate metadata for the classes annotated with #ConfigurationProperties, which is used by IDEs to provide autocompletion and documentation in application.properties, remember to add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

trigger component scan from a application for an included spring boot jar using extra annotations

I need to publish a Spring boot based jar which should be consumed in other Spring/Spring boot based applications.
In my reuse jar I have a class(BusinessConfig) annotated with #Configuration and it gives out two beans. This class is in the base package of the reuse jar.
#Configuration
public class BusinessConfig {
#Bean(name = "BusinessRepoManager")
public BusinessRepoManager businessRepoManager(){
return BusinessRepoManager.getInstance();
}
#Autowired
#Bean(name = "CustomerManager")
#Scope("request")
public CustomerManager customerManager(BusinessRepoManager busrepoManager){
return CustomerManager.getInstance();
}
}
In the second application, I have added the dependency and in the application class I have the statement
#ComponentScan(basePackageClasses = {BusinessConfig.class})
to inform Spring context to look for beans provided in BusinessConfig class as well.
This works well, as I could see the beans getting created.
Is there any possibility to simplify this, should all consuming applications know the class name in which my configuration exists/package name.
I tried creating a custom annotation in the jar project and used that in the consuming application.
#ComponentScan(basePackageClasses = {BusinessConfig.class})
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Component
public #interface EnableDemoBusiness {
}
Then in my consuming application I just added
#EnableDemoBusiness
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Is there any way to get this work ?
Thanks in advance !
You have a couple of options:
Option 1
You can turn your class into "auto-configuration", by creating a META-INF/spring.factories file in your jar with the following content:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.your.package.BusinessConfig
Now in applications using your jar if #EnableAutoConfiguration or #SpringBootApplication annotations are used, your configuration will be processed and the beans created.
You might want to annotate your configuration with some #ConditionalXXX annotations if required to give applications that use your jar more control.
Refer to the documentation for more information.
Options 2
You can create a custom #EnableXXX annotation like you attempted.
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Import(com.your.package.BusinessConfig.class)
public #interface EnableDemoBusiness {
}

Resources