将 @Service 自动装配到第三方库时出现问题
目前,我正在将 Autowiring
myService
集成到我的应用程序中的各种对象中,并且工作正常。
@Autowired
private MyService myService;
使用此配置:
<context:component-scan base-package="com.myapp.mypackage" />
但是,我添加了一个第三方库,并希望将 Autowire
myService
也添加到该包中的某些对象中,但它不起作用。
我对组件扫描进行了此更改,但当我尝试在第三方包中访问 myService
时,我收到了 NullPointerException
:
<context:component-scan
base-package="com.myapp.mypackage, com.thirdparty.thirdpartypackage" />
我认为这会起作用吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 3rd 方库,通常的方法是使用 xml:
您不能依赖注释,因为 3rd 方库很可能不使用
@Autowired
。With 3rd party libraries the usual approach is to use xml:
You can't rely on annotations, because the 3rd party library most likely does not use
@Autowired
.如果第三方包是 spring 管理的,请忽略答案的其余部分
我认为在进行依赖项注入之前你应该问自己的问题是,对象是 spring 管理的吗,要做到这一点,你可以定义它们在 spring context xml 中或使用 (@component , @service springstereo type) 注释对象
让我们看看手头的案例
让我们看一下(MyService)的例子,如果这个服务对象有状态(因为spring对象是单例),而且如果这个服务有没有被注入的协作对象
公共类MyService
{
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
{
您是否尝试过使用适配器模式作为替代方案?我相信您可以在适配器上使用
@Autowired
。Have you tried using the adapter pattern as an alternative? I believe that you can use
@Autowired
on the adapter.