如何从 Spring 应用程序上下文 XML 访问数据库?
我有一些 bean 需要使用另一个必须从数据库加载的 bean。我使用 Hibernate 并有一个用 @Repository 注释的 DAO。
我设法将 bean 定义为单例,并使用 DAO 作为 XML 中的工厂,但由于存储库在 XML 中并不明确,所以我觉得很脏。
是否有更优雅更容易理解的解决方案?
以下是 application-context-beans.xml 的摘录:
<bean id="myBean"
class="myBeanClass">
<property name="defaultMyValue">
<bean factory-bean="myValueDAO" factory-method="getEntity">
<constructor-arg value="0" />
</bean>
</property>
</bean>
myValueDAO 不是在 XML 上定义的,而是在 @Repository 注释的类上定义的
这段代码可以工作,但我不喜欢它,Spring IDE Eclipse 功能也不喜欢它; -)
I have some beans that need to use another bean that must be loaded from database. I use Hibernate and have a DAO annotated with @Repository.
I managed to do it defining the bean as singleton and use the DAO as it's factory in the XML but since the Repositories are not explicit in the XML it feels dirty to me.
Is there a more elegant an easier to understand solution?
Here is an extract of application-context-beans.xml:
<bean id="myBean"
class="myBeanClass">
<property name="defaultMyValue">
<bean factory-bean="myValueDAO" factory-method="getEntity">
<constructor-arg value="0" />
</bean>
</property>
</bean>
myValueDAO is not defined on an XML but a class anotated with @Repository
This code works but I don't like it and the Spring IDE Eclipse feature don't like it either ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种关于您想在 Java 中做多少事情以及在 XML 中做多少事情的审美判断,考虑诸如未来谁将维护它以及他们可能做出什么样的更改等因素。
对于我来说,我不喜欢将普通的旧域对象直接放入上下文配置中,除非它类似于 util:properties ,其中包含我的其他 bean 需要初始化自身的数据。如果使用您现有的解决方案对您来说太像深奥的黑魔法,那么请编写您自己的 FactoryBean,它采用 DAO 实例(如果您愿意,甚至可以自动装配)并返回一个实例
myBeanClass
。It's sort of an aesthetic judgement about how much you want to do in Java and how much in XML, considering factors like who's going to maintain this in the future and what kind of changes they're likely to make.
As for me, I don't like putting plain old domain objects directly in the context configuration unless it's something like a
util:properties
that contains data my other beans need to initialize themselves. If using the solution you have feels too much like deep black magic to you, then write your ownFactoryBean
that takes an instance of the DAO (which can even be autowired if you like) and returns an instance ofmyBeanClass
.仅当您的 bean 是不可变的 Hibernate 对象且不包含依赖的持久 bean/集合时,它才可能有意义。否则,您可能会陷入不同会话和延迟加载异常的问题。您能详细解释一下为什么您使用这种从架构角度令人怀疑的方法吗?
It may only make sense if your bean is an immutable Hibernate object that does not contain dependent persisted beans/collections. Otherwise you may trap into problems with different sessions and lazy-loading exceptions. Could you explain in detail why you use such a doubtful from the architectural perspective approach?