Oliver Drotbohm Archive About Tags

Using Spring's @Configurable in three easy steps

May 25th, 2009

As you might not be aware of, besides injecting dependencies into beans Spring is able to inject dependencies into objects that are not instantiated by Spring. This becomes especially handy if you’re stuck to Domain Driven Design leveraging a rich domain model over an anemic one. As there’s been some buzz around that functionality on twitter, I just put some small quickstart project together that has rather stripped down character but shows all the necessary steps nevertheless. The links to the sources as well as the binaries are attached below. Here is what you essentially have to do.

1. Equip your domain class with @Configurable

The domain class in the sample is org.synyx.samples.spring.atconfigurable.domain.User. Note that we can inject the referenced service by just stating an @Autowired property. No setter needed, no pollution of the domain class’ interface.

2. Enable injecting capabilities in your configuration file

The maven project I have created states a dependency to spring-context that allows two critical declarations: <context:spring-configured /> activates injection into domain classes not managed by Spring. Note that I use <context:component-scan /> in the application-context.xml to pick up the User class as well as GreetingServiceImpl from the service package.

3. Enable load-time weaving

To actually get the injection working you need to weave some Spring aspects in your domain class. While you could do this by compile time weaving, i chose load time weaving as it is much simpler to set up in development environment. To get it up and running you declare <context:load-time-weaver aspectj-weaving="autodetect"/> that pretty much tells Spring to look around for some available load time weaver an use it. The cruicial part now is to activate a Java agent for your runtime that now weaves the aspects into the domain class during class loading. In my case this is done by activating the agent via a command line argument for Maven’s Surefire plugin.

This way you can easily enrich domain objects maybe persisted by Hibernate with domain services managed by Spring

Resources

blog comments powered by Disqus