【问题标题】:Injecting bean declared in xml file using the @Inject annotation使用@Inject注解注入在xml文件中声明的bean
【发布时间】:2013-04-27 16:03:20
【问题描述】:

我无法让@Inject 正常工作。我正在尝试使用 @Inject 注释从 xml 注入一个 bean,但我收到错误消息 "java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required".

我也一直在尝试与@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);

}

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>

干杯!

【问题讨论】:

  • 尝试添加@Component作为类的注解?
  • @Ben 我认为@Repository@Component。我也试过这个,但它没有用,我害怕。还是谢谢!

标签: spring cdi


【解决方案1】:

要摆脱 此位置不允许使用注释 @Qualifier 消息,您必须使用注释 @interface

【讨论】:

    【解决方案2】:

    我设法使用@Inject 将dataSource 注入我的Dao。我使用了@PostConstruct 来实现这一点,如下所示:

    @Inject
    private DataSource dataSource;
    
    @PostConstruct
    private void initialize(){
        setDataSource(dataSource);
    }
    
    DSLContext create = DSL.using(dataSource, SQLDialect.DB2);
    

    我确信有更好的或“更清洁”的方式来实现这一点,但我找不到。 感谢您的建议!

    【讨论】:

      【解决方案3】:

      这在 Spring 中运行良好。我使用@Autowired 注释,而不是@Inject

      【讨论】:

      • 我最好让它与@Inject 一起工作,因为我在整个 DI 应用程序的其余部分都使用它。但是,我尝试使用autowire="byType" 使用@Autowired,但没有雪茄。我会尽量让它工作。 (另外,考虑到我使用第三方类作为数据源,这会被认为是一种好的做法吗?)
      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      相关资源
      最近更新 更多