为什么我不能将Spring Environment对象注入我的bean?

时间:2016-02-23 12:09:53

标签: spring spring-mvc dependency-injection autowired xml-configuration

我在使用Spring框架的Java应用程序中遇到以下问题。

所以我有以下情况,进入 root-context.xml 配置文件我有这个bean配置:

<!-- Definition for datiPianiInterventiDaoImpl bean -->
   <bean id="datiPianiInterventiDaoImpl" class="it.myCompany.myclient.batch.dao.DatiPianiInterventiDaoImpl">
      <property name="dataSource"  ref="dataSource" />    
   </bean>  

好的,所以它工作正常,这个bean被正确创建并且工作正常。

问题是现在在这个bean中我还要注入一个 org.springframework.core.env.Environment Spring类的内容。

所以我试着这样做:

public class DatiPianiInterventiDaoImpl implements DatiPianiInterventiDao {

    @Autowired
    private Environment env;

    ...................................................
    ...................................................
    ...................................................
}

但它似乎无法运作,因为当我执行我的应用程序时,环境环境的值为 null

@Autowired 已激活,因为我在项目的其他类中使用此注释。

那么可能是什么问题?我想也许这可能取决于我将 id =&#34; datiPianiInteventiDaoImpl&#34; 定义到我的 root-context.xml (和这里我也定义了注入这个bean的依赖项)。

所以也许我不能将XML依赖注入与使用 @Autowired 混合使用?

有什么问题?我错过了什么?如何正确地将环境实例注入此类?

2 个答案:

答案 0 :(得分:5)

环境的可能原因为空:

  • 您在Environemnet类之上缺少@Component / @Service注释。
  • 您使用new运算符创建了DatiPianiInterventiDaoImpl类的某个实例。
  • 您的参赛作品:是否与正确的套餐基础相对应?
  • 我假设annotation-config存在,因为@Autowired在别处工作。
  • 尝试使用@Service
  • 注释您的DatiPianiInterventiDaoImpl

答案 1 :(得分:2)

将XML依赖注入与@Autowired的使用混合没有问题。只要你的bean被spring bean工厂扫描,这是一个有效的语法。自动装配环境到Dao classe有问题,看看dave写了什么here,你可以在这个链接中找到解决方案(另一个答案)

相关问题