Rosty Kerei
Rosty Kerei

Reputation: 1034

Hibernate entity autowire

Can you please advice me, how can I nicely enable Spring autowiring for Hibernate entities?

Let's say I have an entity and would like to have mail-sender there:

@Entity
public class EmailActivity extends Activity {
    @Autowired @Transient
    private JavaMailSender javaMailSender;

    ...
}

Is there any better way than doing

AutowireCapableBeanFactory.autowireBean(
    getCurrentSession().get(Activity.class, id)
);

in my DAO?

thanks!

Upvotes: 8

Views: 8490

Answers (3)

stephan f
stephan f

Reputation: 622

There seems to be a better way than using aspectj-weaving, namely using a hibernate LoadEventListener, explained in this post.

Upvotes: 2

sourcedelica
sourcedelica

Reputation: 24040

The way I do it is to use AutowiredAnnotationBeanPostProcessor.

In your entity's constructor you ask the AutowiredAnnotationBeanPostProcessor to inject "this".

My comments at the end of this article details the technique. The article talks about a similar method of autowiring Hibernate entities.

Upvotes: 3

Ralph
Ralph

Reputation: 120781

It is possible! (And it is the default style in Spring Roo!)

All what you need is to add the @Configurable annotation to your Entity. Activate the annotation in the configuration <context:spring-configured/> and using AspectJ weaving.

There is a Chapter in the Spring Reference: 7.8.1 Using AspectJ to dependency inject domain objects with Spring

See also:

BTW I strongly recommend to use AspectJ compile time weaving, when possible.

Upvotes: 9

Related Questions