Reputation: 3666
I have a jar file that contains a java class HelloService
with @Service
annotation. I would like to Autowire it into my a @Component
class GoodByeComponent
that I am writing (autowire into the constructor).
So, the skeleton for HelloService
could look something like this:
@Service
public class HelloService
{
...
}
And the GoodByeComponent
would look like:
import from.some.jar.HelloService
@Component
public class GoodByeComponent
{
private final HelloService helloService;
@Autowired
public GoodByeComponent(HelloService helloService)
{
this.helloService = helloService;
}
}
Understandably, I get an error that says Could not autowire. No beans of 'HelloService' type found.
So. I have some idea that I might need to create a bean somewhere that returns HelloService
? How would I even instantiate the service...? It also needs to autowire other things. Is this possible, or is it too much of a headache and I should probably just copy it into my jar?
Upvotes: 0
Views: 482
Reputation: 343
Your question does not have enough information, but most likely, your application have a @ComponentScan
annotation somewhere in your program. That annotation is responsible for finding your @Component
, @Service
and initializing them.
By default, @ComponentScan
only scan for the its own package. So let say it you have a package structure similar to this:
your.own.package ---- ConfigurationClass
|
--- GoodByeComponent
Then spring naturally, will only discover the GoodByeComponent
and cannot find the HelloService
.
You have to supply additional location for it like:
@ComponentScan({ "your.own.package", "from.some.jar" })
That would allow spring to discover the beans inside your own application, as well as the external dependency you rely on.
Upvotes: 3