2012-09-15 43 views
1

如果spring bean在jar文件中使用了註釋,我怎麼能在我的類中加載我的bean實例?從Jar中加載帶註釋的彈簧bean

在jar文件

package org.java.service.test; 

@Service(value = "MyService") 
public class MyService { 

    @Resource(name = "myproperties") 
    private Properties properties; 
} 

在我的項目

package org.java.project.test; 

@Service(value = "OtherService") 
public class OtherService { 
    @Resource(name = "MyService") 
    private MyService myService; 
} 

在彈簧的beans.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" ....> 

    <context:annotation-config/>  
    <context:component-scan base-package=org.java.service.test, org.java.project.test"/> 
    ..... 
</beans> 

我也嘗試如下,這是行不通的

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" ....> 

    <context:annotation-config/>  
    <context:component-scan base-package="org.java.service.test"/> 
    <context:component-scan base-package="org.java.project.test"/> 
    ..... 
</beans> 
+0

你在使用什麼服務器容器,如何打包jar,你在哪裏放置jar? –

+0

你可以提供異常跟蹤嗎? – sgpalit

+0

你能解決這個問題嗎?我面臨着類似的問題 – CuriousCoder

回答

0

我認爲這個問題不在你的組件掃描配置中。 而不是在您的字段private MyService myService;上使用@Resource註釋,您應使用@Autowired註釋。

所以,現在你在課堂上OtherService代碼就會像下面:

package org.java.project.test; 

@Service(value = "OtherService") 
public class OtherService { 
    @Autowired 
    private MyService myService; 
} 

據我應該爲你工作。去嘗試一下。乾杯。

+0

'@ Resource'的行爲幾乎就像'@ Autowired',所以我認爲它不會有幫助。 – michael

+0

我不確定。 ?試試看吧。 –

+0

感謝您的回答。儘管我嘗試使用@Autowired註解,但我無法加載bean實例。 – CycDemo

0

<context:component-scan> 掃描那些在當前項目中的包。

+0

您是否檢查我的問題?我發佈了兩個類,一個來自項目,另一個來自jar文件。 *在jar文件中**和**在我的項目中**。你不能說**當前項目中的那些包** – CycDemo