43

Is it possible to inject beans to a JPA @Entity using Spring's dependency injection?

I attempted to @Autowire ServletContext but, while the server did start successfully, I received a NullPointerException when trying to access the bean property.

@Autowired
@Transient
ServletContext servletContext;
1

3 Answers 3

55

You can inject dependencies into objects not managed by the Spring container using @Configurable as explained here: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable.

As you've realized by now, unless using the @Configurable and appropriate AspectJ weaving configuration, Spring does not inject dependencies into objects created using the new operator. In fact, it doesn't inject dependencies into objects unless you've retrieved them from the ApplicationContext, for the simple reason that it simply doesn't know about their existence. Even if you annotate your entity with @Component, instantiation of that entity will still be performed by a new operation, either by you or a framework such as Hibernate. Remember, annotations are just metadata: if no one interprets that metadata, it does not add any behaviour or have any impact on a running program.

All that being said, I strongly advise against injecting a ServletContext into an entity. Entities are part of your domain model and should be decoupled from any delivery mechanism, such as a Servlet-based web delivery layer. How will you use that entity when it's accessed by a command-line client or something else not involving a ServletContext? You should extract the necessary data from that ServletContext and pass it through traditional method arguments to your entity. You will achieve a much better design through this approach.

3
  • 6
    Both answers on this question are a perfect example of a useful SO thread (I upvoted both). While @RaviThapliyal 's answer below provides a way to achieve the result, your answer provides contextual background (for me it was an "aha"-experience that helped transforming all the theoretical info about Spring's DI that I've read in the past weeks into practically applicable knowledge). Imo there can't be enough of such posts on SO, because they actually teach something (and more often than not don't earn you much rep.)
    – sthzg
    Sep 13, 2015 at 13:24
  • @sthzg When I feel down and need to regain my confidence, I come back here and read your comment. Thank you.
    – Spiff
    Feb 14, 2019 at 19:39
  • Great answer. I'm just trying to inject gson so I have one instance across app. If this means I have to use/get to learn AspectJ so much the better, as the point of my project is to develop as many features and learn as much as I can while striving for efficiency and elegance. Not sure if AspectJ is overkill and costs performance to just instantiating new gson's but it's worth all things considered
    – gcr
    Jan 14, 2022 at 3:35
21

Yes, of course you can. You just need to make sure the entity is also registered as a Spring managed bean either declaratively using <bean> tags (in some spring-context.xml) or through annotations as shown below.

Using annotations, you can either mark your entities with @Component (or a more specific stereotype @Repository which enables automatic exception translation for DAOs and may or may not interfere with JPA).

@Entity
@Component
public class MyJAPEntity {

  @Autowired
  @Transient
  ServletContext servletContext;
  ...
}

Once you've done that for your entities you need to configure their package (or some ancestor package) for being scanned by Spring so that the entities get picked up as beans and their dependencies get auto wired.

<beans ... xmlns:context="..." >
  ...
  <context:component-scan base-package="pkg.of.your.jpa.entities" />
<beans>

EDIT : (what finally worked and why)

  • Making the ServletContext static. (remove @Autowired)

    @Transient
    private static ServletContext servletContext;
    

Since, JPA is creating a separate entity instance i.e. not using the Spring managed bean, it's required for the context to be shared.

  • Adding a @PostConstruct init() method.

    @PostConstruct
    public void init() {
        log.info("Initializing ServletContext as [" +
                    MyJPAEntity.servletContext + "]");
    }
    

This fires init() once the Entity has been instantiated and by referencing ServletContext inside, it forces the injection on the static property if not injected already.

  • Moving @Autowired to an instance method but setting the static field inside.

    @Autowired
    public void setServletContext(ServletContext servletContext) {
        MyJPAEntity.servletContext = servletContext;
    }
    

Quoting my last comment below to answer why do we have to employ these shenanigans:

There's no pretty way of doing what you want since JPA doesn't use the Spring container to instantiate its entities. Think of JPA as a separate ORM container that instantiates and manages the lifecycle of entities (completely separate from Spring) and does DI based on entity relationships only.

10
  • Unfortunately, servletContext is still null after adding @Component to the entity and <context:component-scan> to app-config.xml.
    – theblang
    May 22, 2013 at 14:08
  • Make it static. private static ServletContext servletContext; If it's still null force the injection by defining a @PostConstruct public void init() { log.info("Initializing ServletContext as [" + MyJPAEntity.servletContext + "]"); } Hope this helps. May 22, 2013 at 14:34
  • It is still null after making it static. I think I am confused about what the @PostConstruct does.
    – theblang
    May 22, 2013 at 16:17
  • @PostConstruct fires init() once the Entity has been instantiated and by referencing servletContext in it, it forces the injection on the (now static) property for the instance created. static was added to make sure it's shared since JPA is creating a separate entity instance i.e. not using the Spring managed bean. May 22, 2013 at 16:28
  • 2
    I consider it a code smell when you have to inject other beans inside your JPA entities and I think it is better to reconsider redesigning your entity and it's surrounding (package-private) classes, instead of injecting other beans inside your entity.
    – davidcyp
    Sep 24, 2018 at 11:31
1

After a long time I stumbled across this SO answer that made me think of an elegant solution:

  • Add to your entities all the @Transient @Autowired fields you need
  • Make a @Repository DAO with this autowired field: @Autowired private AutowireCapableBeanFactory autowirer;
  • From your DAO, after fetching the entity from DB, call this autowiring code: String beanName = fetchedEntity.getClass().getSimpleName(); autowirer.autowireBean(fetchedEntity); fetchedEntity = (FetchedEntity) autowirer.initializeBean(fetchedEntity, beanName);

Your entity will then be able to access the autowired fields as any @Component can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.