Mr Baloon
Mr Baloon

Reputation: 2766

Injecting bean declared in xml file using the @Inject annotation

I can't get @Inject to work properly. I'm trying to inject a bean from xml using the @Inject annotation, but I get the error message "java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required".

I have also been trying in combination with @Qualifier("dataSource"), but wherever I put the @Qualifier it says "The annotation @Qualifier is disallowed for this location".

I have been reading loads of documentation on @Inject and I can't seem to find anything that mentions any special treatment of beans declared in xml.

However, I'm guessing Spring is trying to create the FooDaoImpl bean before scanning the dataSourceBean.

How would I go about using @Inject to inject the dataSource bean declared in the xml file? Is it even possible, using @Inject?

FooDaoImpl.java

@Repository
public class FooDaoImpl extends NamedParameterJdbcDaoSupport implements FooDao {

@Inject
private DataSource dataSource;

DSLContext create = DSL.using(dataSource, SQLDialect.DB2);

}

Spring-Module.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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config /> 
<context:component-scan base-package="com.example.foobar" />

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close"> 
    <property name="driverClass" value="com.ibm.db2.jcc.DB2Driver" />
    <property name="jdbcUrl" value="jdbc:db2://localhost:50000/BLABLA" />
    <property name="user" value="PAPAYA" />
    <property name="password" value="COCONUT" />
</bean>

Cheers!

Upvotes: 3

Views: 3908

Answers (3)

user1126039
user1126039

Reputation: 1

To get rid of the The annotation @Qualifier is disallowed for this location message you have to use the annotation @interface.

Upvotes: 0

Mr Baloon
Mr Baloon

Reputation: 2766

I managed to use @Inject to inject the dataSource to my Dao. I used a @PostConstruct to achieve this, like so:

@Inject
private DataSource dataSource;

@PostConstruct
private void initialize(){
    setDataSource(dataSource);
}

DSLContext create = DSL.using(dataSource, SQLDialect.DB2);

I'm sure there is a better, or "cleaner" way of achieving this, but none that I could find. Thanks for your suggestions!

Upvotes: 0

duffymo
duffymo

Reputation: 308743

This works fine in Spring. I use the @Autowired annotation, not @Inject.

Upvotes: 1

Related Questions