Richo
Richo

Reputation: 761

Can't get Spring dependency Injection to work

I'm pretty much a total beginner to Spring so don't assume that just because I didn't mention something I probably did it anyway.

I'm trying to get dependency injection to work, I got a spring.xml with the following content:

<?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>

and then in my code I have:

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

and when I try to use the conn-object in my code I get a nullpointerexception

Bear in mind that I don't actually know if spring is running, I'm using IntelliJ and it placed 13 spring related jar-files in my lib directory, but I can't really tell if Spring is even trying to inject anything

Upvotes: 0

Views: 925

Answers (2)

Just having Spring in your classpath is not enough to make this work.

You must ask Spring to produce the object you need for any annotations to be honoured. Either this happens in a Spring container, but for stand-alone applications you need to have a Spring context (e.g. AnnotationConfigApplicationContext) and ask it through its getBean() method.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692231

First, your code doesn't compile. It should adhere to JavaBeans conventions, and the method should thus be

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

Now, just because you have a spring XML file and the spring jars in your classpath doesn't make Spring magically run and inject dependencies. You need to load an application context, and load at least one bean from this context. This bean will have all its dependencies injected, recursively.

See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-instantiation for an example.

Upvotes: 0

Related Questions