JPA @Entity中的Bean注入 [英] Bean injection inside a JPA @Entity
问题描述
是否可以使用Spring的依赖项注入将bean注入到JPA @Entity
中?
我尝试使用@Autowire ServletContext,但是尽管服务器确实成功启动,但是在尝试访问bean属性时收到了NullPointerException.
@Autowired
@Transient
ServletContext servletContext;
您可以使用@Configurable
将依赖项注入不受Spring容器管理的对象中,如下所述: 解决方案
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.
这篇关于JPA @Entity中的Bean注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!