views:

925

answers:

3

Is there a recommend way to get Spring 2.5+ to autowire Hibernate (3.0+) domain objects. I realize that there is a way to do this using AspectJ (@Configurable), but I would like to avoid pulling in AspectJ.

Some Googling found this DependencyInjectionInterceptorFactoryBean class but it seems to just live in the sandbox (and just in 2.0.x?).

I can create a 10-line Hibernate PreLoadEventListener to do this autowiring for me, but I really assumed it would be something that org.springframework.orm.hibernate3 provided.

A: 

Could you give a code example?

I find the whole 'anaemic domain model' anti-pattern difficult to implement. I think it sounds great in theory but not so great in practice.

What factors have led you to take a rich domain model approach?

"The [...] anti-pattern is difficult to implement? This sounds strange. Is this what you wanted to say ?
Pascal Thivent
+1  A: 

Take a look at the @Repository (and @Component) annotation(s). With Spring 2.5, the concept of "stereotype" annotations introduced in Spring 2.0 has been extended and these annotations are all supported by the new component-scan functionality as explained in the Annotation-driven configuration chapter of Spring documentation.

So this should work:

@Repository
public class HibernateClinic implements Clinic {

    private SessionFactory sessionFactory;

    public HibernateClinic(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Collection getVetTypes() {
        Session session = sessionFactory.getCurrentSession();
        return session.createQuery(”from VetTypes”).list();
    }
}

(Sample taken from Rossen Stoyanchev's presentation at Metropolis 2008)

Pascal Thivent
A: 

The recommended way to provide dependency injection to instances beyond Spring's control is to use the AspectJ-based solution you mentioned. As far as I know, the Hibernate-specific classes have been abandoned in favour of the general approach described here.

Also note that you don't need @Configurable if you use AbstractInterfaceDrivenDependencyInjectionAspect. As you said, you will need to use AspectJ either for load-time or compile-time weaving. As a benefit, you will get dependency injection for "corner cases" like deserialization as well with that approach.

For a comprehensive example of how the patterns suggested by Ramnivas can be implemented and integrated, have a look here.

springify