簡體   English   中英

將@Service自動裝配到第三方庫時出現問題

[英]Problem autowiring a @Service into a third party library

目前,我正在將myService Autowiring到應用程序中的各種對象中,並且工作正常。

@Autowired
private MyService myService;

使用此配置:

<context:component-scan base-package="com.myapp.mypackage" />

不過,我添加了一個第三方庫,並希望Autowire myService到該包中也有一些對象,但它不工作。

我對組件掃描進行了此更改,但是當我嘗試在第三方程序包中訪問它時,我得到了myServiceNullPointerException

<context:component-scan 
base-package="com.myapp.mypackage, com.thirdparty.thirdpartypackage" />

我以為這行得通嗎?

對於第三方庫,通常的方法是使用xml:

<bean class="com.thirdparty.Foo">
    <property name="somePropertyWithASetter" ref="myService" />
</bean>

您不能依賴注釋,因為第三方庫很可能不使用@Autowired

如果第三方軟件包是春季托管的,請忽略其余答案

我認為在進行依賴項注入之前,您應該問自己的問題是,是否對Spring對象進行管理,為此,您可以在spring上下文xml中定義它們,或者使用(@component,@service spring立體聲類型)注釋對象。

讓我們看看手中的情況

  1. 您可以訪問此第三方源代碼嗎?
  2. 第三方是否使用依賴項注入?
  3. 如果以上問題的答案是否定的,那么這樣做並不容易。
  4. 讓我們看一下(MyService)的示例,如果該服務對象具有狀態(因為spring對象為單例),又如果該服務具有未注入的協作對象,該怎么辦?

    公共類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; } 

您是否嘗試過使用適配器模式作為替代? 我相信您可以在適配器上使用@Autowired

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM