At the moment I'm Autowiring
myService
into various objects in my app and it works fine.
@Autowired
private MyService myService;
using this config:
<context:component-scan base-package="com.myapp.mypackage" />
However, I've added a third party library and want to Autowire
myService
into some objects in that package also but it's not working.
I made this change to my component scan but I'm getting a NullPointerException
for myService
when I try to access it in the third party package:
<context:component-scan
base-package="com.myapp.mypackage, com.thirdparty.thirdpartypackage" />
I thought this would work?
With 3rd party libraries the usual approach is to use xml:
<bean class="com.thirdparty.Foo">
<property name="somePropertyWithASetter" ref="myService" />
</bean>
You can't rely on annotations, because the 3rd party library most likely does not use @Autowired
.
If the third party package is spring managed, Please ignore the rest of the answer
I think the question you should ask yourself before do dependency injections is, Is the object spring managed, To do that either you define them in spring context xml or annotate the object with (@component , @service spring stereo type)
Let's look at the case in hand
Let's look at the example of (MyService), what if this service object has state (since spring objects are singleton), Also if this service has collaborating objects that are not being injected
public class MyService {
//depending on how MyServiceOne is managed makes it hard to retrofit //MyService as a spring bean private MyServiceOne serviceone; //this also would have an adverse affect if you try use this as a spring managed //since all spring beans are singleton private String someState; }
Have you tried using the adapter pattern as an alternative? I believe that you can use @Autowired
on the adapter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.