开发者

How can I access database from spring application context XML?

开发者 https://www.devze.com 2023-03-13 18:00 出处:网络
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 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.

I开发者_开发技巧s 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 ;-)


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 own FactoryBean that takes an instance of the DAO (which can even be autowired if you like) and returns an instance of myBeanClass.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消