2012-01-01 28 views
0

我几乎是Spring的初学者,所以不要以为我没有提到我可能做过的事情。无法获得Spring依赖注入工作

我试图让依赖注入的工作,我有以下内容的spring.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.1.xsd"> 

<context:annotation-config/> 
<bean id="connection" class="richo.project.ConnectionImpl"/> 
</beans> 

,然后在我的代码有:

private IConnection conn; 
@Resource(name="connection") 
public void setConn(IConnection conn){ 
this.conn = conn; 
} 

当我尝试在我的代码中使用conn对象我得到一个nullpointerexception

请记住,我实际上并不知道如果弹簧运行,我使用IntelliJ,它放置了13个与弹簧相关的jar文件在我的lib目录中,但我无法确定Spring是否尝试注入任何东西

回答

2

只要在你的类路径中有Spring是不足以使这项工作。

必须要求Spring产生你需要的对象,以便对任何注解进行优化。这种情况发生在Spring容器中,但是对于独立应用程序,您需要有一个Spring上下文(例如AnnotationConfigApplicationContext)并通过它的getBean()方法询问它。

+0

因此,类中的注释只有在Spring实例化时才有效,这意味着如果我仅仅使用新的,spring将会没有阅读这些注释? – Richo 2012-01-01 13:48:16

+0

Guice的确如此。我不确定Spring是否属于这种情况(关于_how_很多classloader魔术的问题已经到位)。 – 2012-01-01 13:50:59

+1

@Richo:是的,Spring只注入它创建的bean。你实例化自己的豆不会被注入。 – 2012-01-01 13:54:29

0

首先,您的代码无法编译。应该坚持JavaBean规范,因此该方法应该是

public void setConn(IConnection conn){ 
    this.conn = conn; 
} 

现在,仅仅因为你有一个春天的XML文件,并在类路径中春瓶不作春神奇运行,并注入依赖。您需要加载应用程序上下文,并从此上下文中加载至少一个bean。这个bean将递归地注入所有的依赖项。

查看http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-instantiation为例。

+0

如果你指的是“voidSetConn”,那么这是一个错字,我已经在我的问题中纠正 – Richo 2012-01-01 13:49:39