2015-06-23 35 views
0

我其中有一個彈簧安置應用Rest Controller如下服務豆Spring不休息正常自動連接控制器

@RestController 
public class IngestorController 
{ 
    @Autowired 
    private IngestorService ingestorService; 

    @RequestMapping(value = "/ingestor/createAndDeploy/{ingestorName}", method = RequestMethod.POST) 
    public void createAndDeploy(@PathVariable String ingestorName) 
    { 
     ingestorService.createAndDeploy(ingestorName); 
    } 

} 

Simlilarly我有一個Service Bean如下

@Service 
public class IngestorService 
{ 
    @Autowired 
    private IngestorCommandBuilder ingestorCommandBuilder; 

    private String uri; 
    private DeployTemplate deployTemplate; 

    public void init() throws URISyntaxException 
    { 
     deployTemplate = new DeployTemplate(new URI(uri)); 
    } 

    @Transactional 
    public void createAndDeploy(Ingestor ingestor) 
    { 
     //..... 
    } 

} 

我有Spring config爲以下顯示

<bean id="ingestorCommandBuilder" class="org.amaze.server.ingestor.IngestorCommandBuilder" /> 

<bean id="ingestorService" class="org.amaze.server.service.IngestorService" init-method="init"> 
    <property name="uri" value="http://localhost:15217" /> 
</bean> 

<bean id="ingestorController" class="org.amaze.server.controller.IngestorController"/> 

有時我嘗試啓動應用程序上下文開始的應用程序上下文,並且它觸及IngestorService中的init方法,也爲該服務bean啓動deployTemplate對象。

但是這個bean對於IngestorController並不是自動裝配的。當我從郵遞員到剩下的端點時,服務bean的deployTemplate屬性爲null ..在Controller中分配給ingestorService變量的對象是一個不同的對象,而不是爲init方法調用的對象...

我試圖使服務豆單(即使默認範圍是單身),但力工作...

我無法找出我做了錯誤的。任何建議表示讚賞...

+0

爲什麼你有''聲明並用'@ Service'註解了這個類? –

+0

您是否在使用任何

+0

您好,感謝您的回覆...是的,我正在使用上下文組件掃描... \t

回答

0

如果你使用基於註釋的配置,你主要是不需要描述應用上下文xml文件中的所有bean。註釋是自動裝配服務所需的全部。

要正確定義init方法,請使用@PostConstruct註釋。屬性可以很容易地移動到externat .properties文件中,並通過@Value註釋注入到代碼中。

或者,使用@Qualifier@Autowired

+0

感謝您的建議,但由於某些原因,我無法使用註釋配置。我只需要通過xml配置來完成此操作... –

+1

您的代碼已經使用了Spring註釋,比如'@ Service'和'@ Autowired'。 – Everv0id

-1

當您使用基於Annotation的DI時,不需要在XML中定義bean。

@PostConstruct可以用來代替你的xml config的init方法。

只需使用

<context:component-scan base-package="..."/> <mvc:annotation-driven/> 
0

首先確保您有:

<context:annotation-config /> 

在你的Spring配置。現在你有severael選擇:

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

掃描組件,或

<!-- autowiring byName, bean name should be same as the property name annotate your ingestorservice with @Service("ingestorServiceByName") --> 
<bean name="ingestorServiceByName" class="your.package.com.IngestorService" autowire="byName" /> 

<!-- autowiring byType, tif there are more bean of the same "general" type, this will not work and you will have to use qualifier or mark one bean as @Primary --> 
<bean name="ingestorServiceByType" class="your.package.com.IngestorService" autowire="byType" /> 

<!-- autowiring by constructor is similar to type, but the DI will be done by constructor --> 
<bean name="ingestorServiceConstructor" class="your.package.com.IngestorService" autowire="constructor" /> 

請附上您的全Spring配置,使其更容易分析您的問題。