JPA @Entity 内的 Bean 注入 [英] Bean injection inside a JPA @Entity

查看:36
本文介绍了JPA @Entity 内的 Bean 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Spring 的依赖注入将 bean 注入 JPA @Entity?

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

我尝试@Autowire ServletContext 但是,虽然服务器确实启动成功,但我在尝试访问 bean 属性时收到了 NullPointerException.

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;

推荐答案

您可以使用 @Configurable 将依赖项注入到不受 Spring 容器管理的对象中,如下所述:http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable.

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.

正如您现在已经意识到的,除非使用 @Configurable 和适当的 AspectJ 编织配置,否则 Spring 不会将依赖项注入使用 new 运算符创建的对象中.事实上,除非您从 ApplicationContext 中检索到它们,否则它不会将依赖项注入对象,原因很简单,它根本不知道它们的存在.即使您使用 @Component 注释您的实体,该实体的实例化仍将由您或 Hibernate 等框架通过 new 操作执行.请记住,注释只是元数据:如果没有人解释该元数据,它不会添加任何行为或对正在运行的程序产生任何影响.

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.

说了这么多,我强烈建议不要将 ServletContext 注入到实体中.实体是域模型的一部分,应该与任何交付机制分离,例如基于 Servlet 的 Web 交付层.当它被命令行客户端或其他不涉及 ServletContext 的东西访问时,您将如何使用该实体?您应该从该 ServletContext 中提取必要的数据,并将其通过传统方法参数传递给您的实体.通过这种方法,您将获得更好的设计.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆