Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot component scan include a single class [duplicate]

I am using spring component scan to auto detect beans as:

@ComponentScan({"com.org.x, com.org.y"})

The issue is I want all classes in com.org.x to be scanned but I want a single class, com.org.y.SomeService.class, alone to be scanned from com.org.y

How can I achieve this ?

Also apart from using context scan, how can I created this bean and inject in the application context ?

like image 698
Anand Sunderraman Avatar asked Jun 10 '16 22:06

Anand Sunderraman


People also ask

What is the difference between @component and ComponentScan?

@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.

What is @configuration @EnableAutoConfiguration and @ComponentScan?

@ComponentScan - to enable component scanning, all the packages and subpackages will be auto-scanned which are under the root package on which @SpringBootApplication is applied. @EnableAutoConfiguration - to enable auto-configuration of the. classes bases on the jars added in classpath.

Can we use component scan in Spring boot?

Using @ComponentScan in a Spring Application. With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

When should I use ComponentScan?

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.


2 Answers

@Import(com.org.y.SomeService.class) works in my case (even when SomeService is a @Service, not a @Configuration)

like image 197
Lu55 Avatar answered Oct 23 '22 09:10

Lu55


You should just define your bean using a method annotated with @Bean in your configuration class, as explained in the documentation.

like image 24
JB Nizet Avatar answered Oct 23 '22 10:10

JB Nizet