8

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!

Rosty Kerei
  • 1,014
  • 1
  • 9
  • 16
  • 1
    Putting a mail sender into an entity seems like an odd choice. Can you describe a little more about why you want that approach? It's obviously not to persist the instance since it's marked transient, and it's not because you're using a non-anemic pattern like active record (since you mention a DAO). Why not inject the mail sender into a manager/service layer with a method exposed to pass the appropriate activity data to be emailed? – Jeff Apr 08 '11 at 12:27
  • related: http://techblog.bozho.net/?p=180 – Bozho Apr 08 '11 at 12:42
  • I think mail sender is an infrastructure. Domain model should not depend to infrastructure code – Adi Sembiring Apr 08 '11 at 15:26
  • oh, come on guys, it's just an example. Actually my EmailActivity is not real entity, it's just a wrapper (@Discriminator) over Activity and sure mail sender is not stored in Db – Rosty Kerei Apr 11 '11 at 17:44

3 Answers3

9

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Ralph
  • 118,862
  • 56
  • 287
  • 383
3

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.

sourcedelica
  • 23,940
  • 7
  • 66
  • 74
2

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

Community
  • 1
  • 1
stephan f
  • 589
  • 5
  • 16