Tuesday, September 26, 2006

Spring, DDD and AspectJ - An Example

In my last post, I discussed the possibilty of using AspectJ with Spring to inject domain objects with service objects to create a richer domain model. This follow up is to explore some example code based on a Customer -> Account example given by Ramnivas.

In this example, we are trying to get the net worth of a Customer object. A Customer object has a relationship with an Account object, but it only has a reference to the Account object's id:

public class Customer {
    
    private Long accountId;

    public Long getAccountId() {
        return accountId; }
    }

    public void setAccountId(Long accountId) {
        this.accountId = accountId;
    }
    ...
}

The value of the account is used to determine the customer's net worth. Suppose we have a CustomerService interface that exposes this operation via its getNetWorth(Customer) method. One implementation of this method would be to place most of the logic in the service layer like this:

public Double getNetWorth(Customer customer) {
    Long accountId = customer.getAccountId();
    Account account = accountRepository.getAccountById(accountId);
    return account.getValue();
}

This is a classic example of an anemic domain model. All of the business logic is in the service layer and the domain objects are simply data containers. But in OO, an object = data + behavior, right? So how do we push this behavior back to the domain layer?

This biggest question in this particular scenario is how can a Customer object obtain a reference to its Account object? Well, there are several ways:
  1. It could be given a reference to the Account object by the CustomerService object. But that really isn't much different than the example above. The CustomerService class is still two involved in the business logic.
  2. This Customer object could actively obtain a reference to the AccountRepository via a service locator. But this introduces a dependency not only on the AccountRepository, but the service locator as well - not a very transparent solution.
  3. The AccountRepository object could be supplied to the Customer object using dependency injection. This makes sense - after all, we are doing this with our Spring beans already in our service/data access layers.
Implementing option #3 is where AspectJ comes in. While Spring manages the lifecycle of service and data access beans, it does not manage the lifecycle of domain objects. These can be instantiated via new or by another framework, such as Hibernate. However, AspectJ can weave advice into the domain object's classes that is executed after their constructor completes. There are several pieces to this puzzle. First let's take a look at the "enriched" SmartCustomer class:

@Configurable("smartCustomer")
public class SmartCustomer extends Customer {

    private AccountRepository accountRepository;

    public AccountRepository getAccountRepository() {
        return accountRepository;
    }

    public void setAccountRepository(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    public Double getNetWorth() {
        Account account = accountRepository.getAccountById(getAccountId());
        return account.getValue();
    }

}

Now a Customer object can obtain a reference to its associated Account object via the AccountRepository. But how does it obtain a reference to the AccountRepository? Notice the @Configurable annotation. This is basically a marker that identifies this class as needing to be configured by Spring whenever a new instance is created. This "magic" is possible because AspectJ weaves in advice into the SmartCustomer's constructor. I have not delved into the details, but I suppose this advice is aware of the Spring application context.

Spring knows how to configure each instance of this class from a prototype bean configured in the application context:

<bean id="smartCustomer" abstract="true" class="org.springdallasug.aspectj.domain.SmartCustomer" scope="prototype" >
    <property name="accountRepository" ref="accountRepository" />
</bean>

Now every instance of the SmartCustomer class will be wired with an AccountRepository object. In order to make this happen, AspectJ must weave this advice into the SmartCustomer class. For my demo, I chose to use load time weaving. This is done by starting the JVM with the following option:

-javaagent:PATH_TO_JAR/aspectjweaver-1.5.0.jar

This enables AspectJ to weave advice into classes as they are being loaded into the JVM. For anybody interested, I have packaged up this simple demo. The entire mechanics behind this can be found in the Spring documentation.

So, it is pretty cool that Spring + AspectJ makes it straightforward to apply dependency injection to domain objects. But the question remains, is this the right thing to do? Taking the example above, allowing a Customer object to completely contain the logic of calculating its own net worth means it needs access to its Account object. But this, in turn, means giving it access to the AccountRepository. This is, for me at least, an unusual design decision. While this does create a "richer" domain model, at adds more (potentially complex) dependencies into the domain model.

I don't think the answer is cut and dry. Instead, it probably needs to be fleshed out in a "real world" application. I just might have to try that.

Edit:
Craig Walls pointed out a couple of improvements to this example. First, I added the name of the prototype bean to the annotation to be more explicit (I also added the "id" attribute to the SmartCustomer bean in the Spring configuration file). Second, I made the prototype bean abstract, which prevents the Spring container from ever instantiating an instance - it is now strictly a prototype. Not a big thing, but it is an improvement. Thanks Craig.

15 comments:

Anonymous said...

All Wrong, at first,your domain model 'Customer ' is wrong:

Customer should refer to Account object, not Account's accountId.

Anonymous said...

dating boot camps [url=http://loveepicentre.com/]saratov dating agency[/url] std dating http://loveepicentre.com/ potassium argon dating

Anonymous said...

Hey,

Do you guys watch movies in theater or on internet? I use to rent DVD movies from [b]Bigflix.com[/b]. Recently I discovered that we can watch all new movies on internet on day, they are released. So why should I spend money on renting movies??? So, can you guys please tell me where I can [url=http://www.watchhotmoviesfree.com]watch latest movie Battleship 2010[/url] for free?? I have searched [url=http://www.watchhotmoviesfree.com]Youtube.com[/url], [url=http://www.watchhotmoviesfree.com]Dailymotion.com[/url], [url=http://www.watchhotmoviesfree.com]Megavideo.com[/url] but, Could not find a good working link. If you know any working link please share it with me.


Thanks

Anonymous said...

travel to nyc for new years http://atravel.in/vacation-packages_chicago-vacation-packages french law regarding reimbursement of travel expenses
[url=http://atravel.in/vacation-packages_nj-shore-vacation-packages]travel writers picks for accomodation in san francisco[/url] travel air line deals to brazil [url=http://atravel.in/cruise_rhapsody-of-the-seas-cruise-liner-what-location-is-it-at-now]rhapsody of the seas cruise liner what location is it at now[/url]
longmont travel http://atravel.in/maps_activities-to-do-with-1st-graders-with-maps
[url=http://atravel.in/tour_agent-singapore-tour]travel network online[/url] tony heavy travel [url=http://atravel.in/tour_george-strait-tour-stops]george strait tour stops[/url]
north dakota travel http://atravel.in/plane-tickets_military-discount-for-plane-tickets how does blood travel through the heart [url=http://atravel.in/adventure_adventure-games-pc-download]adventure games pc download[/url]

Anonymous said...

dress shoes http://topcitystyle.com/women-page36.html gucci black backpack [url=http://topcitystyle.com/?action=products&product_id=957]wholesale replica chanel handbags[/url] designer dining room tables
http://topcitystyle.com/red-long-sleeve-tops-color8.html seersucker clothes [url=http://topcitystyle.com/grey-versace-color1.html]web site designer software[/url]

Anonymous said...

stockcar racing http://carautonews.in/acura/acura-service-coupons-los-angeles-oc dodge ram brake pedal pivot bushing
[url=http://carautonews.in/bike/paisley-wood-bike-trail]dodge dakota long bed truck definition[/url] innovations auto loan [url=http://carautonews.in/bentley/rent-a-bentley-in-pittsburgh-pa]rent a bentley in pittsburgh pa[/url]
classic mercedes http://carautonews.in/daewoo/daewoo-tv-manual-21
[url=http://carautonews.in/cadillac/cadillac-sts-for-sale-in-washington]mercedes benz command unit 2004[/url] dodge tonneau covers [url=http://carautonews.in/bikes/chevy-powered-bikes]chevy powered bikes[/url]
hotwiring a mercedes ml320 http://carautonews.in/auto-com/cars-auto-borgward-isabella
[url=http://carautonews.in/auto-net/auto-seam-sealer]automobile clockspring[/url] indianapolis 500 automobile race winning history [url=http://carautonews.in/eagle/seal-fly-like-an-eagle]seal fly like an eagle[/url]

Anonymous said...

lbfm porn xxx http://theporncollection.in/gay-movie/the-office-gay-witch-hunt
[url=http://theporncollection.in/mature-woman/mature-bukake]adult entertainment show[/url] solar screen lubricant [url=http://theporncollection.in/gay-male/film-gay-italiano-italian-house-youporn]film gay italiano italian house youporn[/url]
sexy fat ladies calendar http://theporncollection.in/lubricant/coconut-extract-lubricant-spray
[url=http://theporncollection.in/lesbian-sex/hot-lesbian-girls]sailing adult[/url] amateur hand [url=http://theporncollection.in/gay-movie/mr-gay-europe]mr gay europe[/url]
little girls hentai http://theporncollection.in/lesbian-porn/beauty-lesbian-only-download-free-video
[url=http://theporncollection.in/porn-galleries/kitchen-staff-porn]video weird colors porn sites[/url] teen eaony porn [url=http://theporncollection.in/gay-love/amature-18-gay-vid]amature 18 gay vid[/url]
huntington beach adult education http://theporncollection.in/lesbian-sex/free-lesbian-anime-games
[url=http://theporncollection.in/gay-boy/gay-justin-timberlake-sex-story]anal vibrator[/url] adult tattoo and piercing photos [url=http://theporncollection.in/hentai-sex/sexy-hentai-anime-babes]sexy hentai anime babes[/url]

Anonymous said...

moto q mobile 6 cdma http://www.orderphonetoday.com/t2000-quad-band-dual-card-with-wifi-analog-tv--item71.html mobile library jobs [url=http://www.orderphonetoday.com/tv-e75-quad-band-dual-card-with-bluetooth--item110.html]location of abercombre and fitch in mobile alabama[/url] virginia cell mobile phone providers

Anonymous said...

porn with bondage http://xwe.in/erotic-video/erotic-topless-wrestling
[url=http://xwe.in/bdsm/female-wrestling-bdsm-melbourne]adult diapers and temperature rectally[/url] adult web sight [url=http://xwe.in/adult-xxx/adult-trish-stratus]adult trish stratus[/url]
group adult free sample http://xwe.in/orgy/movie-trailers-bath-lesbian-orgy
[url=http://xwe.in/gay-boy/free-gay-men-xxx-streamers]men enoy anal sex[/url] captive guys in pain free adult sites [url=http://xwe.in/thongs/topless-thongs-heels]topless thongs heels[/url]
girls with a dildo http://xwe.in/adult-xxx/adult-masturbate
[url=http://xwe.in/erotic-video/male-erotic]goron hentai[/url] only amateur clips [url=http://xwe.in/erotic-gay]erotic gay[/url]
barely legal anal http://xwe.in/ass-sex/black-ass
[url=http://xwe.in/fetish/fetish-dominatrix-agency-boston]adult entertainment puerto vallarta[/url] adult costumes porn [url=http://xwe.in/condom/her-plesure-condoms]her plesure condoms[/url]

Anonymous said...

high school musical movie pictures [url=http://worldmovs.co.cc/full_version-10--000-bc/9459database/]10, 000 BC[/url] as good as it gets movie [url=http://worldmovs.co.cc/full_version-une-histoire-sans-importance/7177database/]Une Histoire Sans Importance[/url]
apocalyto movie tribe [url=http://worldmovs.co.cc/full_version-stargate-atlantis--s04e14-/14158database/]Stargate Atlantis (S04e14)[/url] john chapman movie [url=http://full-length-movies.com/dvd-quality-movie-american-pie-beta-house/12475database/]American Pie Beta House[/url]
director of the movie 13 going on 30 [url=http://full-length-movies.com/dvd-quality-movie-varg-veum--bitre-blomster/12807database/]Varg Veum: Bitre Blomster[/url] super bad movie merchandise [url=http://worldmovs.co.cc/full_version-/178database/][/url]
movie ordinary people synopsis [url=http://worldmovs.co.cc/full_version-american-pie-1-2-3-4-5-6/3966database/]American Pie 1,2,3,4,5,6[/url] john holmes movie trailer [url=http://worldmovs.co.cc/full_version-letter-to-jane/24096database/]Letter to Jane[/url]

Anonymous said...

floridas supplemental health insurance medicare from disabilty [url=http://usadrugstoretoday.com/products/clozaril.htm]clozaril[/url] ogagi skin care medical spas new york new york http://usadrugstoretoday.com/products/sarafem.htm
us diabetic supply [url=http://usadrugstoretoday.com/categories/perdida-de-peso.htm]perdida de peso[/url] calculating maximum heart rate zones [url=http://usadrugstoretoday.com/products/zebeta.htm ]fda medical equipment [/url] teenagers drugs
donepezil fda approval [url=http://usadrugstoretoday.com/tos.htm]no prescription pharmacies[/url] tricare drugs approved http://usadrugstoretoday.com/products/bystolic.htm
uk medicine donations to africa [url=http://usadrugstoretoday.com/products/motrin.htm]motrin[/url] chai tea wholesale [url=http://usadrugstoretoday.com/products/ed-discount-pack-3.htm ]what does vitamin b do for your body [/url] breast implants in houston

Anonymous said...

lopilato evista caraws [url=http://usadrugstoretoday.com/products/betnovate.htm]betnovate[/url] medical tools dealers and thier email address contacts in london http://usadrugstoretoday.com/categories/de-la-salud-de-la-mujer.htm
mild positive ana blood test results [url=http://usadrugstoretoday.com/products/valtrex.htm]valtrex[/url] women doctor interviews on their experiences in medical field [url=http://usadrugstoretoday.com/products/brand-tamiflu.htm ]touch of health day spa [/url] heart palpitations and dizziness
blueberry movie drugs [url=http://usadrugstoretoday.com/products/bactroban.htm]bactroban[/url] bundle branch block heart rate http://usadrugstoretoday.com/products/serevent.htm
what happens when prostate is removed [url=http://usadrugstoretoday.com/products/viagra-soft-flavoured.htm]viagra soft flavoured[/url] adult generic medical release form [url=http://usadrugstoretoday.com/products/brand-viagra.htm ]ginger health [/url] kidney reflux

Anonymous said...

vaccination requirements thailand travel http://xwl.in/inn/country-inn-and-suites-and-stone-mountain-ga independent travel packages
[url=http://xwl.in/car-rental/internet-discounts-car-rental-specials-ny]free travel brochure new york[/url] portable travel printers [url=http://xwl.in/flight/discount-student-flight]discount student flight[/url]
stroke association insurance travel http://xwl.in/cruises/cruises-around-europe
[url=http://xwl.in/expedia/corporate-travel-agency-expedia-service-business]travel vacations riviera[/url] montana travel guitar [url=http://xwl.in/car-rental/advantage-car-rental-cancun]advantage car rental cancun[/url]
travel returns http://xwl.in/motel/brights-hotel-motel-loganville-georgia passport travel info [url=http://xwl.in/travel/travel-statistics-2002]travel statistics 2002[/url]

Anonymous said...

presque isle casino http://xwn.in/roulette_true-odds-of-roulette baccarat mini online free casino games
[url=http://xwn.in/joker_pascal-picotte-joker]pennsylvania cash 4 lottery[/url] guide to us casinos and racinos [url=http://xwn.in/online-casino_mount-airy-casino-opening-date]mount airy casino opening date[/url]
casino surveillance pay scale http://xwn.in/lottery_winning-daily-lottery
[url=http://xwn.in/slot_door-mail-slot-sarasota]denali road lottery pass[/url] indiana river boat casinos [url=http://xwn.in/gambling-online_gambling-and-sports]gambling and sports[/url]
bingo calling cards to sell http://xwn.in/roulette_gambling-bonus-internet-roulette casino games slots slot machines [url=http://xwn.in/blackjack_blackjack-for-fun]blackjack for fun[/url]

Anonymous said...

report illegal gambling in florida http://wqm.in/jackpot_jackpot-t-shirt-and-lounge-pants wife sues husband lottery
[url=http://wqm.in/poker-online_seneca-poker]no download casino bonus[/url] foxwoods casino philadelphia [url=http://wqm.in/casino-online_bet-royal-casino-bonus]bet royal casino bonus[/url]
blackjack online gambling play http://wqm.in/joker_joker-picture
[url=http://wqm.in/keno_keno-analyis]samsung blackjack phone information[/url] uk lottery board official site [url=http://wqm.in/slot_agp-slot]agp slot[/url]
sports gambling web site http://wqm.in/joker_harley-davidson-joker-card betting line of nfl playoffs [url=http://wqm.in/slots_types-of-agp-slots-computer]types of agp slots computer[/url]