Spring boot component scan include a single class [duplicate]
Asked Answered
A

2

24

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 ?

Alita answered 10/6, 2016 at 22:7 Comment(4)
Why use a scan if you just want a single bean. Just define your bean using an @Bean annotated method in your configuration class. docs.spring.io/spring/docs/current/spring-framework-reference/…Maiocco
@JBNizet can you provide me a snippet for itAlita
I included a link to the documentation, which contains snippets, explanations, and everything.Maiocco
@JBNizet can you post it as an answer so I can accept itAlita
M
4

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

Maiocco answered 10/6, 2016 at 22:18 Comment(2)
What about @Component that has @Autowired fields?Culpa
Yep. Same for the non-default constructor: if the SomeService has parameters in constructor you have to copy them to the instantiating @Bean method.Tricyclic
T
31

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

Tricyclic answered 25/5, 2018 at 17:46 Comment(2)
I didn't know that one can even import @Services. This is especially helpful if one can't call a constructor due to visibility restrictions.Cimmerian
or @Import(value = { Class1.class, Class2.class })Gardol
M
4

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

Maiocco answered 10/6, 2016 at 22:18 Comment(2)
What about @Component that has @Autowired fields?Culpa
Yep. Same for the non-default constructor: if the SomeService has parameters in constructor you have to copy them to the instantiating @Bean method.Tricyclic

© 2022 - 2024 — McMap. All rights reserved.