2012-09-15 47 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