Home > Net >  What is the correct annotation so I can get Autowired EntityManagerFactory?
What is the correct annotation so I can get Autowired EntityManagerFactory?

Time:03-08

I need to get an autowired EntityManagerFactory in a class which is being used in my Spring boot application. I think the problem is stemming from the fact that my class is in a separate package.

I generated a simple sample case to illustrate what I am trying to do.

Here is the application class:

package test;

import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import test2.GetEMF;

@SpringBootApplication
public class AutoWiredTest implements CommandLineRunner {
  @Autowired
  private EntityManagerFactory emf;

  @Override
  public void run(String... args) 
  throws Exception {
    if( emf == null )
      System.out.println("Top: EMF is null");
    else
      System.out.println("Top: Got EMF instance");      
    new GetEMF();
 }
  
  public static void main(String[] args) 
  throws Exception {
    SpringApplication.run(AutoWiredTest.class, args);
  }
}

Here is the GetEMF class in a different package:

package test2;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;

@PersistenceContext
public class GetEMF {
  @Autowired
  private EntityManagerFactory emf;
  
  public GetEMF() {
    if( emf == null )
      System.out.println("Inner: EMF is null");
    else
      System.out.println("Inner: Got EMF instance");      
  }
}

When I run the code, I get this output:

Top: Got EMF instance
Inner: EMF is null

From reading online, I thought the @PersistenceContext annotation would fill in the emf, but it is no.

I know it looks like I can simply pass a reference for the emf to the GetEMF constructor, but that is a quirk of the simple test case. It won't work for my application. I have to get an EntityManagerFactory from the environment.

CodePudding user response:

The emf field in GetEMF is null because you have created the instance yourself:

new GetEMF();

If you want Spring to inject dependencies, for example into @Autowired fields, then the instance needs to be a bean managed by Spring.

You could annotate GetEMF with @Component and then autowire it into AutoWiredTest.

  • Related