Why AutoConfigurationPackages not consider #ComponentScan? - spring-boot

Spring Boot's support for Spring data configuration is generally by org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport, and this class use the follow code to determine what packages to scan for repositories:
AutoConfigurationPackages.get(this.beanFactory)
So, basically Spring Data with Spring Boot only scan the package which contains the #EnableAutoConfiguration or #ImportAutoConfiguration, but not consider the #ComponentScan, Is this correct ?

The #ComponentScan annotation is a core Spring Framework feature to search for classes annotated with #Component. Since Spring Data repositories are interfaces (and not annotated), the #ComponentScan annotation won't pick them up.
If you are using Spring Data outside of Spring Boot, you can scan for Spring Data repositories using #EnableJpaRepositories with the basePackages attribute set.
When it comes to Spring Boot, there's usually no need to use either #ComponentScan or #EnableJpaRepositories. If you structure your code as suggested, both components and repositories will be picked up.
To get back to your original question about AbstractRepositoryConfigurationSourceSupport. If you look at the source of #SpringBootApplication you'll see it's annotated with #ComponentScan (to find #Components) and #AutoConfigurationPackage (via #EnableAutoConfiguration). The #AutoConfigurationPackage sets up AutoConfigurationPackages with the value that's later retrieved.
If you want to override the packages the Spring Data searches for repositories (for example in tests) you'll need to use #EnableJpaRepositories to completely override auto-configuration. I usually don't do this, but instead use #DataJpaTest and pick up my main configuration.

Related

Spring boot Jpa is not working with Spring batch and spring integration

I am working with spring batch. I needed to add some jpa repositories. So previously i was using JDBCTemplate which was working fine.
But when I started working with JPA, the spring boot application could not find the repos. Which were there.
#Autowired
ClassLevelConfigRepo clcr;
I checked these things as the best practices.
Added #EnableJpaRepositories in springBoot application class.
Added #Repostiories to the repository interfaces.
extended the interfaces with JpaRepository<Account, String>
Added #Entity to the entity classes and defined the #Table and # Column annotations properly.
But I am still getting below error.
Field clcr in com.cloudtask.batchconfig.util.LhmUtility required a bean of type 'com.cloudtask.batchconfig.repo.ClassLevelConfigRepo' that could not be found.
I tried checking all the dependencies in pom.xml it was as per recommended. And I have all the tables defined properly in data base.
I was expecting the application to return the Autowired clcr object propely.
Edit 1 : spring boot application annotations
#SpringBootApplication
#ComponentScan({"com.cloudtask"})
#EnableAsync
#IntegrationComponentScan({"com.cloudtask"})
#EnableIntegrationManagement(defaultLoggingEnabled = "true")
#EnableJpaRepositories
#EntityScan
public class imclassApplication ```
When you work with Spring Data Jpa with those basic points you should also keep track of below points.
you have added spring-boot-starter-data-jpa in your pom.xml
you have added the entity and repo package below one level of the application package.
If you the package is at same level you should specify the exact package details in the annotation. in your case it should be like :
#EnableJpaRepositories("com.cloudtask.batchconfig.repo")
#EntityScan(basePackages = {"com.cloudtask.batchconfig.entity"})
Happy programming!

Prevent AutoConfiguration of all included Spring Cloud dependencies

Excluding several AutoConfiguration classes in Spring Boot is easy. Just exclude it from the application:
#SpringBootApplication(exclude = {
org.springframework.cloud.autoconfigure.RefreshAutoConfiguration.class,
org.springframework.cloud.openfeign.FeignAutoConfiguration.class,
})
But how can all AutoConfiguration from the package org.springframework.cloud can be excluded without adding all Spring Clouds AutoConfiguration classes to the exclude? That would be dozens if not hundred entries. And it would not be future proof as with every new Spring Cloud version new AutoConfiguration classes come along.
Using #ComponentScan would only work if #SpringBootApplication respective #EnableAutoConfiguration is not used. But that would remove all the convenient auto configuration capabilities, too.
Is there a way to achieve that programmatically? And how?
Removing Spring Clouds dependencies from the application is unfortunately not a feasible solution.
Why you want to exclude all classes from auto configuration ?
Most of the beans in Autoconfigurations are #conditional , they will not be created if you are providing your own.
Anyway you can look into AutoConfigurationImportSelector . As of now Spring boot allow only class and name for #EnableAutoConfigurtion exclude . if you want to write customize "AutoConfigurationImportSelector" , you can subclass and filter exclude by package after writing your own extended interface for EnableAutoConfiguration to write package method.
As I mentioned this will be the last thing I would like to do . just check #conditional dependency for auto configuration and provide your own beans is better solution.

Spring boot auto configuration with dependency and without #ComponentScan

Spring boot provides #ComponentScan to find packages to be scanned.
I am building a library which has #RestControllers inside with package com.mylib.controller. There are other classes as well with stereotype annotations in different packages.
So, if some one is developing SpringBoot Application with com.myapp base package.
He uses my library in his application. He need to mention #ComponentScan("com.mylib") to discover stereotype components of library.
Is there any way to scan components without including library package in #ComponentScan?
As spring-boot-starter-actuator expose its endpoints just with dependency, without defining #ComponentScan. OR any default package which is scanned regardless of application base package.
You could create a Spring Boot Starter in the same style as the Spring Provided Starters. They are essentially a jar'd library with a a spring.factories file pointing to the #Configuration class to load with some other annotations on there to provide overriding/bean back off (#ConditionalOnMissingBean) and generally provide their own #ConfigurationProperties.
Stéphane Nicoll provided an excellent demo of how to build one.
https://github.com/snicoll-demos/hello-service-auto-configuration
It is also documented in the Spring Boot documentation. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html
The library approach would also work but I see no benefit in not making it a starter. Additionally for any library/starter I'd recommend dropping the #ComponentScan and just defining the beans in a #Configuration. This will work for sterotypes like #RestController etc. will function as normal if you create an #Bean out of it in a configuration.
Spring boot starter are special artifacts designed by Spring and used by Spring.
You can check that in the source code that contains mainly a
spring.provides file :
provides: spring-boot-actuator,micrometer-core
I don't know the exact way to process in the same way as Spring Boot Starter but as probably acceptable workaround, you could define in your jar a #Configuration class that specifies #ComponentScan("com.mylib").
#Configuration
#ComponentScan("com.mylib")
public class MyLibConfig {
//...
}
In this way, clients of the jar need "only" to import the #Configuration class :
#Import(MyLibConfig.class)
#Configuration
public class ClientConfig{
//...
}

why do we need componentScan in spring

This question might be trivial but still i'm unable to find a good reason or best practice towards #ComponentScan in Spring
DI works just by self annotating the class then why do we need #ComponentScan
What is the best practice towards this?
#ComponentScan tells Spring in which packages you have annotated classes which should be managed by Spring.
Spring needs to know which packages contain spring beans, otherwise you would have to register each bean individually in(xml file). This is the use of #ComponentScan.
Take a simple example, you have a class and annotated with #Controller in a package package com.abc.xyz; , you have to tell the spring to scan this package for Controller class, if spring didn't scan this package, then spring will not identifies it as a controller class.
Suppose if your dealing with configuration file,
<context:component-scan base-package="com.abc.xyz">
like this,
When spring loads the xml file, this tag will search the all the classes present in the package com.abc.xyz, so any of the class containing #controller, #Repository #Service etc.., if it found then spring will register these annotated class in the bean factory.
Suppose if your using spring boot application,
Then your spring-boot application is annotated with The#SpringBootApplication.
#SpringBootApplication annotation is equivalent to using #Configuration, #EnableAutoConfiguration and #ComponentScan with their default attributes.
One more point if you didn;t specify the base package name in #ComponentScan,
it will scan from the package, where the #Springbootapplication present

Spring #ComponentScan annotation

Why do we use #ComponentScan annotation in spring ? I am not being able to figure out the exact difference between context:componentscan in xml file and #ComponentScan annotations in java and how to use them in case of classes which have been annotated with #Configuration
In short, there is no difference.
#ComponentScan - Used with #Configuration classes, for example, when you have java-based configurations for Spring.
It provides support parallel with Spring XML's <context:component-scan> element. The purpose of those two are exactly the same - to scan spring components.
But there is one advantage of xml based configuration - you don't need to compile your java code. When you added some package under <context:component-scan> then you don't need to compile java source code. Place the xml configuration file in your server and restart it.

Resources