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

And*_*ili 2 spring dependency-injection spring-mvc 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>  
Run Code Online (Sandbox Code Playgroud)

好的,它可以正常工作,并且此bean已正确创建并正常工作。

问题是,现在在这个bean中,我还必须注入org.springframework.core.env.Environment Spring类的实例。

所以我尝试用这种方式做:

public class DatiPianiInterventiDaoImpl implements DatiPianiInterventiDao {

    @Autowired
    private Environment env;

    ...................................................
    ...................................................
    ...................................................
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用,因为当我执行应用程序时,Environment env的值为 null

@Autowired被激活,因为我使用此批注在其他班级啊,我的项目。

那么可能是什么问题呢?我想,也许它可以通过这样的事实依赖,我定义我有豆ID =“datiPianiInteventiDaoImpl”到我 root-context.xml中(在这里我还定义了注入该bean的依赖项)。

所以也许我不能将XML依赖注入与 @Autowired

怎么了?我想念什么?如何将Environment实例正确地注入此类?

mle*_*ski 5

环境为空的可能原因:

  • 您在Environemnet类的顶部缺少@Component / @Service批注。
  • 您使用新的运算符在某个地方创建了类DatiPianiInterventiDaoImpl的实例。
  • 您输入的内容是否对应于正确的包装基础?
  • 我假设存在注释配置,因为@Autowired在其他地方均可使用。
  • 尝试使用@Service注释您的DatiPianiInterventiDaoImpl