无法让 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-object,我得到一个nullpointerexception

请记住,我实际上不知道spring是否正在运行,我使用IntelliJ,它在我的lib目录中放置了13个spring相关的jar文件,但我不能真的告诉spring是否甚至试图注入任何

仅仅在你的类路径中有Spring是不够的。

必须要求Spring生成您需要的对象,以便支持任何注释。这可能发生在Spring容器中,但对于独立应用程序,您需要有一个Spring上下文(例如AnnotationConfigApplicationContext)并通过其getBean()方法询问它。

首先,您的代码无法编译。它应该遵循JavaBeans的约定,因此方法应该是

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

现在,仅仅因为在类路径中有一个spring XML文件和spring jar文件,并不能使spring神奇地运行并注入依赖项。您需要加载应用程序上下文,并从该上下文加载至少一个bean。这个bean将以递归的方式注入它的所有依赖项。

最新更新