Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 458
Rosty Kerei Avatar asked Apr 08 '11 12:04

Rosty Kerei


1 Answers

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:

  • http://www.chrissearle.org/node/285
  • http://www.olivergierke.de/wordpress/2009/05/using-springs-configurable-in-three-easy-steps/

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

like image 194
Ralph Avatar answered Oct 02 '22 07:10

Ralph