2013-05-03 130 views
3

我無法讓@Inject正常工作。我正在嘗試使用@Inject註釋從xml注入bean,但我收到了錯誤消息 "java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required"使用@Inject註釋注入xml文件中聲明的bean

我也一直在嘗試與@Qualifier("dataSource")結合,但無論我把@Qualifier它說"The annotation @Qualifier is disallowed for this location"

我一直在閱讀關於@Inject的大量文檔,我似乎無法找到任何提及在xml中聲明的任何特殊處理的bean。

不過,我猜測Spring在掃描dataSourceBean之前正試圖創建FooDaoImpl bean。

我該如何去使用@Inject注入xml文件中聲明的dataSource bean? 它甚至有可能使用@Inject

FooDaoImpl.java

@Repository 
public class FooDaoImpl extends NamedParameterJdbcDaoSupport implements FooDao { 

@Inject 
private DataSource dataSource; 

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

} 

彈簧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> 

乾杯!

+0

嘗試添加「@ Component」作爲類的註釋嗎? – 2013-05-03 09:37:59

+0

@我覺得'@ Repository'是一個'@ Component'。我也嘗試過這種方法,但恐怕沒有用。不管怎麼說,還是要謝謝你! – Roger 2013-05-03 10:10:57

回答

0

我設法使用@Inject將dataSource注入到我的Dao中。我用了一個@PostConstruct實現這一點,就像這樣:

@Inject 
private DataSource dataSource; 

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

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

我敢肯定有一個更好的,或「清潔劑」實現這一目標的方式,但沒有,我能找到。 感謝您的建議!

1

這在春天很好。我使用@Autowired註釋,而不是@Inject

+0

我最好把它和'@Inject'一起使用,因爲我在整個應用程序的其餘部分都使用了這個。但是,我使用'autowire =「byType」'嘗試了'@ Autowired',但沒有使用雪茄。我會盡力讓它工作。 (另外,考慮到我使用第三方類作爲數據源,這會被認爲是一種好的做法嗎?) – Roger 2013-05-03 10:23:56

0

要擺脫註釋@Qualifier對於此位置不允許使用消息,您必須使用註釋@interface