簡體   English   中英

如何在另一個類中使用@Service注釋類作為@Autowired bean,該類位於Service類的組件掃描包之外?

[英]How to use @Service annotated class as an @Autowired bean in another class which is outside the component scan package of the Service class?

我有一個名為ABCService的服務接口及其實現,稱為ABCServiceImpl。

ABCService.class

package com.abc.service.ABCService;

public interface ABCService{
    //interface methods
}

ABCServiceImpl.class

package com.abc.service.ABCServiceImpl; 

@Service
public class ABCServiceImpl implements ABCService{
     // implemented methods
}

XYZ.class

package com.abc.util.XYZ;

public class XYZ{

  @Autowired
  ABCService abcService;

  //methods
}

應用程序的context.xml

<context: annotation-config>
<context: component-scan base-package="com.abc.service, com.abc.util"/>

但是,當我嘗試在類XYZ中使用自動裝配的ABCService訪問接口ABCService中的方法時,我得到一個空指針異常。 然后我從ABCServiceImpl中刪除了@Service注釋,並將application-context.xml中的實現文件作為bean添加並為類XYZ創建了一個bean,並將ABCServiceImpl的bean引用到了類XYZ的bean; 它解決了這個問題

應用程序的context.xml

<bean id="abcService" class="com.abc.service.ABCServiceImpl" />

<bean id="xyz" class="com.abc.util.XYZ" >
    <property name="abcService" ref="abcService"></property>
</bean>

但我想使用@Service注釋本身而不在application-context.xml中顯式定義bean。 我該怎么做?

如果你想在沒有包掃描的情況下自動裝配bean,或者用XML定義它們,那么你唯一的選擇就是使用Spring API以編程方式進行...

這可以使用

XYZ bean = new XYZ();
context.getAutowireCapableBeanFactory().autowireBean(bean);

此外,如果您想要調用任何@PostConstruct方法,請使用

context.getAutowireCapableBeanFactory().initializeBean(bean, null);

暫無
暫無

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

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