Sharing common Spring Boot configuration between projects - java

The app I'm working on has a maven dependency on a common module containing a dozen spring-boot #Configuration beans specifying datasources, LDAP contexts, security modules, property sources etc which I often want to suppress.
My app and this common module are part of a spring-boot maven multi-module project. My sub-project needs about 6 of the 12 configuration beans.
I have got quite a long way using #Import and #SpringBootApplication#exclude and #ImportAutoConfiguration:
#Import({PropertySpringConfig.class,
LdapConfig.class,
SecurityConfig.class,
JpaDataConfiguration.class,
RestConfiguration.class,
WebConfigurer.class})
#SpringBootApplication(exclude = {
RefDataSourceConfig.class,
ElasticsearchAutoConfiguration.class,
CamelAutoConfiguration.class,
ElasticsearchDataAutoConfiguration.class})
public class MyRestApplication {
public static void main(String[] args) {
SpringApplication.run(MyRestApplication.class, args);
}
}
and a test configuration bean that all my JPA tests import (I have others, e.g. for REST tests):
#Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
CacheAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class,
TestDatabaseAutoConfiguration.class,
TestEntityManagerAutoConfiguration.class })
public class TestJpaConfiguration {}
The whole codebase was set up with Spring 1.3.x. I upgraded it to Spring 1.4.x.
Take for example one of the datasources, a configuration bean in the shared dependency - I don't need it, and it prevents Spring Boot autoconfiguration because it's marked with #Primary (possibly unnecessarily).
I don't want Spring Boot in my sub-project to see it when it runs autoconfiguration, but how do I share it from the common module with the other Spring Boot sub-projects that do need it?
I could split it out into its own maven project and only have it as a dependency in the sub-projects that needed it. But there are 11 other similar configuration beans! It could be seen as overkill although I like this approach - but I have 5 colleauges to convince.
I can just struggle on using #SpringBootApplication#excludes for the code and #ImportAutoConfiguration for the tests - but then I miss out on the Spring Boot benefits like #DataJpaTest or #JsonTest test slices
I could repeat the configuration beans in each project where they are needed - a bit of cut & paste - but I like this option the least.
Is there a 4?

Related

Can spring boot's #Autowired inject dependencies from a jar(included in classpath) which is using GUICE for DI?

I have a base package which is using guice for DI. I am using this as a library in my other project where I am using Spring boot So can I autowire dependencies from that jar to my spring boot project.
Let's say the artifact of the base package is com.package.dependency and my spring boot project is com.example.spring-boot
I have tried
#ComponentScan(basePackages = {"com.example.spring-boot","com.package.dependency"})
but it does not work.
You should be able to autowire dependencies from an external jar by using componentscan if there are classes annotated as autowire candidates (#Bean, #Component,..)
#ComponentScan would not find any candidates for autowiring unless there are any candidates which are qualified for autowiring is available in the external library.
Instead, you can define an #Bean annotation and return a new instance of the class you want to return in your #Configuration class.
#Configuration
public class MyConfig {
#Bean
public MyExternalBean myExternalBean() {
return new MyExternalBean();
}
}
and in the class you need to use it, write :
#Autowired
private MyExternalBean myExternalBean;
If you need autoconfiguration, refer : https://docs.spring.io/spring-boot/docs/2.0.0.M3/reference/html/boot-features-developing-auto-configuration.html. Here, you make use of spring.factories and specify the classes available for autoconfiguration so that you need not specify #ComponentScan in every project you use that external jar (applicable when the jar is developed by you or your company for use in other projects and not for third-party jars).

Spring Integration Testing does not pick up JPA beans from other modules

I have a multi module maven project. In one module I have all my persistence stuff like entities and repositories and in another module I import that persistence module and I want to run some integration tests.
The problem is that my tests do not pick up repositories and can't create the context because of the missing beans. Can someone help me with what I am missing?
The project structure looks like this
persistence module
business logic module
web module
In my business logic module pom I import the persistence module
<dependency>
<groupId>com.acme</groupId>
<artifactId>persistence</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
My integration tests configuration
#Configuration
#ComponentScan({"com.acme.persistence", "com.acme.business"})
#EnableAutoConfiguration
public class DataTestConfig {
}
and all my tests are annotated with the following
#SpringJUnitConfig(DataTestConfig.class)
#DataJpaTest
If I move all the persistence module inside the business module then the tests work fine, but I want to keep them in separate modules.
Thanks
I found the solution.
I added #EnableJpaRepositories on my test configuration class.
This way repositories were created and now my services that used repositories can be instantiated.
This is how the final integration testing configuration looks like
#Configuration
#ComponentScan({"com.acme.persistence", "com.acme.business"})
#EntityScan("com.acme.persistence")
#EnableJpaRepositories(basePackages = "com.acme.persistence")
#EnableAutoConfiguration
public class DataTestConfig {
}

Spring boot custom starter - Cannot import custom starter class

I am developing a spring boot custom starter which pom contains some dependencies (other starters, libraries) and this starter does some config about jwt filtering to allow the filter at security level. The issue is when I add my custom starter as a pom dependency in another project (starter-consumer), it seems it detects the class I want to import but IntelliJ does nothing.
Maybe I didn't packaged the starter correctly, or at least the classes that I coded inside. The other dependencies that the starter contains in the pom are successfully added as a dependencies of the starter-consumer. For example, I use some jwt utils which dependency is in the parent starter. So that thing works ok.
import io.jsonwebtoken.impl.DefaultClaims;
The problem is when I try to import a custom class which I coded in the starter. This is my package structure:
I want to use the JwtConfig class in my starter-consumer. It appears but I can't import. It does nothing.
And then If I manually check package availability I see this:
Pepito is missing :( and theinit is the package name of the starter-consumer. The jar is installed in the local m2 so I get the dependency like this:
<dependency>
<groupId>com.pepito</groupId>
<artifactId>starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
Any insights on this?
Edit 1:
I removed the boot maven plugin as a you said, it seems now it is not packaged as boot app and my starter-consumer can import the clases I coded . One additional thing, what happens with beans? Does the autoconfigure starts the bean by itself or the starter-consumer needs to declare it?
Edit 2:
So as part of the solution of this post, I am trying to inject a bean from the starter into the starter-consumer.
Apart from another beans, here we have the jwtTokenAuthenticationFilter which I want to inject into my starter-consumer security config.
#Configuration
#ConditionalOnProperty(name = "security.jwt-enabled", havingValue = "true")
public class JwtAutoConfiguration extends AbstractHttpConfigurer<JwtAutoConfiguration, HttpSecurity> {
#Bean
public JwtConfig jwtConfig() {
return new JwtConfig();
}
#Bean
public FilterRegistrationBean registration(#Qualifier("jwtFilter") JwtTokenAuthenticationFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
#Bean
public JwtTokenAuthenticationFilter jwtFilter() {
return new JwtTokenAuthenticationFilter(jwtConfig());
}
#Override
public void init(HttpSecurity http) throws Exception {
// initialization code
}
}
This is my spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.pepito.starter.configuration.security.jwt.JwtAutoConfiguration
And in the starter-consumer I have the following
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtTokenAuthenticationFilter jwtFilter;
And here is where I see the error in intellij that can't autowire that bean because it does not exist. I suppose is because of something about scan but in my starter-consumer I have #SpringBootApplication which is suppose it contains componentscan annotation.
I believe A couple of issues that I see here and some clarifications will help you to find an answer:
Module with starter is a regular jar. The only thing that differs is that it has META-INF/spring.factories which I see exist.
Having said that - I see in the Pepito starter module class SpringBootMicroserviceStarterApplication. This is wrong. If the starter is a spring boot application, then the chances are that you're using spring boot maven plugin to prepare it as an application.
But the jar created by this plugin is not really a Jar, more specifically it stores other jars in BOOT-INF lib and in general can't be considered a Jar build-tool-wise and IDE-wise.
To put it simple you cannot declare a dependency on something that gets packaged as a spring boot application!
Update 1
To address your OP's question in comments:
The starter is not a spring boot application. It should not have a method annotated with #SpringBootApplication, it should not be packaged as spring boot application and so forth.
The best way to view the starter is as an self-contained "feature" or "facility" (trying to find the most appropriate word in English) that can be used by Spring boot applications by importing the starter module.
In terms of testing, #SpringBootTest should not be used in starter's module because it mimics the startup of spring boot application which obviously does not exist here.
Its possible to test it with Unit Test or with Spring Testing Framework:
#RunWith(SpringRunner.class)
#ContextConfiguration(<here comes the class of AutoConfiguration in starter)
One last thing to clarify here:
In spring Factories you can specify the autoconfiguration that in turn declares a series of beans required by the starter.
These beans are resolved by spring boot application just like other beans, the difference is that the Configuration is identified out of spring.factories file and not by package structure or explicit configuration.
So to answer your question:
Would you know if I can declare a bean in the starter and then autowire it in the consumer?
Yes, as long as the starter gets loaded by spring boot application, you can autowire (or inject in any other way) beans from starter into the beans of the spring boot application itself.

APPLICATION FAILED TO START due to same bean

I have a Spring Webflux application where I am trying to load a dependency from an old module (old module is on Spring WebMVC framework).
When the application is launched, this error is thrown -
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'requestMappingHandlerAdapter', defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/web/reactive/config/DelegatingWebFluxConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
I want all the beans from webflux package to be initiated, so I can't set spring.main.allow-bean-definition-overriding=true.
Also tried excluding all classes within org.springframework.boot at the time of component scan - #ComponentScan(excludeFilters = #Filter(type = FilterType.REGEX, pattern = "org.springframework.boot*").
Also tried excluding all spring packages in pom.xml of my webflux project like this -
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
Since I cannot modify the older dependency project to webflux, are there any options I could use the make the code work ?
In your springboot startup class , the #EnableAutoConfiguration annotation will auto configure the mvc part (WebMvcAutoConfiguration will fail due to same bean name in DelegatingWebFluxConfiguration)
So try ti exclude this from auto config and try as below
#SpringBootApplication
#EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class })
public static void main(String[] args) {
...
SpringApplication.run(MyApp.class, args);
}
If I understand correctly you have some Web-related dependencies on the classpath but aren't building a web application, you can explicitly tell SpringApplication that you don't want a web application:
app.setWebEnvironment(false);
This is the way to disabling Web-related auto-configuration as it means you don't need to know what those auto-configuration classes are and lets Spring Boot take care of it for you.
As mentioned in your problem description, Using dependencies of Spring MVC in Spring Webflux can cause this issue. I have solved this issue by excluding the group "org.springframework.boot" while including the old dependency.
In gradle.build i have did something like below:
implementation("dependency-using-spring-mvc") {
exclude(group= "org.springframework.boot")
}

Spring Boot Autowiring of beans is not working in maven multi module project

While modularising our project into different independent maven projects using spring boot and maven, we have came across a issue where autowiring of beans in multi module maven project is not working.
Just to give you an overview of the issue, below are the independent maven projects developed so far
Coreservices – Contains spring boot domain objects of whole application : Output JAR
DBservices1-Contains spring boot repositories and services(Database Services) to access database : Output JAR
Rewards -Contains Rewards module related files(Controllers, services(Business Logic Services), Views) : Output JAR
RewardsApp- Independent deployable maven project : Output WAR
Below is the dependency structure
RewardsApp-> Rewards -> DBservices1 -> Coreservices
The problem is #Autowired annotation used in Rewards and DBservices1 to fetch the mapped services annotated with #Service/#Repository are not available in RewardsApp Project.
As a workaround we have configured the beans in RewardsApp with #Bean annotation, then the services are available to the server to start successfully.
With this approach we need to manually configure all the beans in RewardsApp used in dependent projects.
We have many services and repositories in our application and we think creating beans like this not a proper way as many beans need to be created.
Please note that we have created all the spring boot controllers,services,repositorys across all projects under
package com.company.application
Below is the snippet of main class:
#SpringBootApplication
#ComponentScan(basePackages = {"com.company.application"})
public class RewardsApp extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(RewardsApp.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RewardsApp.class);
}
}
/**
*Manual beans in RewardsApp
**/
#Bean
public SomeService someService()
{
return new SomeService();
}
By adding below annotation in RewardsApp.java did the trick for me, now autowiring was working for the classes inside the jars
#ComponentScan(basePackages = {"com.company"})
#EntityScan(basePackages = {"com.company"})
#EnableJpaRepositories(basePackages = {"com.company"})
I guess above are for Services,Entities(Domains),Repositories
How about having a configuration class (with relevant comp scans) for each module and importing those configs into your application class?
#SpringBootApplication
#ComponentScan(...)
#Import({RewardsContext.class, DBservicesContext.class})
...
Import docs here

Categories

Resources