Skip to content
Advertisement

How can I autowire a service that is imported from another jar?

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:

JavaScript

And the GoodByeComponent would look like:

JavaScript

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?

Advertisement

Answer

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:

JavaScript

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.

See: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement