AndreaNobili
AndreaNobili

Reputation: 42957

Why I can't inject a Spring Environment object into my bean?

I have the following problem in a Java application that use Spring framework.

So I have the following situation, into the root-context.xml configuration file I have this bean configuration:

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

Ok so it works fine and this bean is correctly created and works fine.

The problem is that now in this bean I have to inject also an intance of the org.springframework.core.env.Environment Spring class.

So I try to do in this way:

public class DatiPianiInterventiDaoImpl implements DatiPianiInterventiDao {

    @Autowired
    private Environment env;

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

But it seems can't work because, when I perform my application the value of the Environment env is null.

The @Autowired is activated because I use this annotation in other classes o my project.

So what could be the problem? I am thinking that maybe it could depend by the fact that I define my bean having id="datiPianiInteventiDaoImpl" into my root-context.xml (and here I am defining also the dependency to inject into this bean).

So maybe I can't mix the XML dependency injection with the use of @Autowired?

What is wrong? What am I missing? How can I correcctly inject the Environment instance into this class?

Upvotes: 3

Views: 6428

Answers (2)

Hezi Schrager
Hezi Schrager

Reputation: 421

There is no problem to mix the XML dependency injection with the use of @Autowired. As long as your bean is scanned by spring bean factory this is a valid syntax. There was a problem with autowiring Enviroment to Dao classe, see what dave wrote here, you can find a solution in this link ( the other answer)

Upvotes: 3

mlewandowski
mlewandowski

Reputation: 802

Possible causes of Environment being null:

  • You are missing @Component / @Service annotation on top of Environemnet class.
  • You created somewhere instance of class DatiPianiInterventiDaoImpl using new operator.
  • Does your entry: corresponds to the proper package base?
  • I assume annotation-config is present since @Autowired works elsewhere.
  • Try to annotate your DatiPianiInterventiDaoImpl with @Service

Upvotes: 6

Related Questions