Stop Spring Boot from loading #Configuration file from dependency module (jar) - java

I'm implementing a Spring boot application with a dependency to another spring module (jar) containing an #Configuration (AmcConfiguration.class) file I do NOT want loaded into the context. I've tried many variations of exclude examples
a few of which are as follows:
//exclude problem configuration class
#SpringBootApplication(exclude={AmcConfiguration.class})
and...
//exclude problem bean from within problem configuration class
#EnableAutoConfiguration
#Configuration
#ComponentScan(excludeFilters = #Filter(type = FilterType.ASSIGNABLE_TYPE, classes = IAmsClient.class))
and...
//exclude problem configuration class package
#EnableAutoConfiguration
#Configuration
#ComponentScan(excludeFilters = #Filter(type = FilterType.REGEX, pattern="com.prot.mtrx.amc.config.*"))
Also, I've made sure there are no package naming collisions.
spring boot root = "com.prot.am.*
dependency = "com.prot.mtrx.amc.*"
I've been searching examples for a few days now and am running out of options. I went down the auto-configuration path but that seems much too complicated a solution to tell spring boot to not run one simple configuration class.
From my logs, it looks like it might be embedded tomcat:
DEBUG o.a.tomcat.util.digester.Digester - New match='mbeans-descriptors/mbean/operation/parameter'
DEBUG o.s.c.a.ClassPathBeanDefinitionScanner - Identified candidate component class: file [C:\TestSuite\workspace-dev\MAMClient\target\classes\com\prot\mtrx\amc\config\AmcConfiguration.class]
What am I missing?

Related

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")
}

Why is this #ComponentScan not working in my spring boot application?

I am learning spring boot. This is my spring boot project structure. I do intentionally keep my application.java in a different package to learn about #ComponentScan
Project source - https://github.com/kitkars/spring-boot
project structure
Error :
The application failed to start due to below error.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field productRepository in com.test.service.ProductService required a bean of type 'com.test.repository.ProductRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.test.repository.ProductRepository' in your configuration.
Process finished with exit code 1
This is my Application.java
#SpringBootApplication
#ComponentScan(basePackages = "com.test")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Now If I move my Application.java under com.test, everything works just great.
What If my Application.java is not under com.test - can it not use the ComponentScan packages and start from there? All the controller, services, repositories etc are present under com.test.
The class annotated with #SpringBootApplication should be in your root package (by default all classes in this package and subpackages are scanned) or you need to specify other packages (controller, entity and others) in #ComponentScan.
Official documentation states:
We generally recommend that you locate your main application class in a root package above other classes.
Spring Boot relies heavily on default configuration. Consider this excerpt from #EnableAutoConfiguration annotation.
The package of the class that is annotated with
#EnableAutoConfiguration, usually via #SpringBootApplication, has
specific significance and is often used as a 'default'. For example,
it will be used when scanning for #Entity classes. It is generally
recommended that you place #EnableAutoConfiguration (if you're not
using #SpringBootApplication) in a root package so that all
sub-packages and classes can be searched.
The same logic implies to #ComponentScan, #EnableJpaRepositories and the above mentioned #EntityScan annotations. So, if you want to take control of component scanning, you should specify base packages explicitly for all of those annotations.
#SpringBootApplication(scanBasePackages = "com.test")
#EnableJpaRepositories(basePackages = "com.test")
#EntityScan(basePackages = "com.test")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also note that in your case there is no need to use another #ComponentScan as you can provide arguments to Spring Boot's #ComponentScan via scanBasePackages attribute.
Please check the dependency 'org.springframework:spring-context-indexer if you have one, of course. In my case, this library has caused problems with submodules.
The problem was that only beans of the current gradle project were included in the index.
resolving do this in my application class.
#Configuration
#SpringBootApplication
#ComponentScan(basePackages = "{lamc.bar.*}")
For me, removing the #ComponentScan did the job.
SpringBoot should pick up all your components automatically, so long as your application structure is like this:
|-->package1
|-->package2
|Main.java
You should remove #Repository in com/test/repository/ProductRepository.java.

NoSuchBeanDefinitionException for a repository in a library

I created a library for sharing code over multiple Spring Boot applications.
The library contains a Repository class RequestRepository. After adding the library to the Spring Boot project, it compiles and runs unit tests successful.
// Library: RequestRepository.java
package org.test.lib;
public interface RequestRepository extends CrudRepository<Request, Integer> {}
// Application: Application.java
package org.test.app;
#SpringBootApplication
#ComponentScan(basePackages = {"org.test.app", "org.test.lib"})
public class Application {
// ...
}
Starting the application raises a NoSuchBeanDefinitionException when Spring tries to autowire the repository.
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'org.test.lib.repositories.RequestRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
I enabled DEBUG logging for the component scan and got the following output regarding the repository.
2018-07-10 08:33:25.035 DEBUG 14976 --- [ main]
.i.s.PathMatchingResourcePatternResolver : Resolved location pattern
[classpath*:org/test/lib/**/*.class] to resources [URL
[jar:file:/C:/Users/.../lib-request-1.0.0-SNAPSHOT.jar!/org/test/lib/repositories/RequestRepository.class],
...
Did I miss something?
You have to enable the repositories outside of your Spring Boot application with #EnableJpaRepositories explicitly.
#SpringBootApplication
#EnableJpaRepositories(basePackages = {"org.test.app", "org.test.lib"})
#ComponentScan(basePackages = {"org.test.app", "org.test.lib"})
public class Application {
// ...
}
See Spring guide.
By default, Spring Boot will enable JPA repository support and look in
the package (and its subpackages) where #SpringBootApplication is
located. If your configuration has JPA repository interface
definitions located in a package not visible, you can point out
alternate packages using #EnableJpaRepositories and its type-safe
basePackageClasses=MyRepository.class parameter.
For using #Entity classes from the library set #EntityScan.

Sharing common Spring Boot configuration between projects

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?

Categories

Resources