Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime dependency injection with Spring

My current project is leveraging Spring, and our architect has decided to let Spring manage Services, Repositories and Factory objects, but NOT domain objects. We are closely following domain driven design. The reasoning behind not using spring for domain objects is primarily that spring only allows static dependency injection. What i mean by static dependency injection is that dependencies are specified inside xml configuration and they get "frozen".

I maybe wrong, but my current understanding is that even though my domain only leverages interfaces to communicate with objects, but spring's xml configuration forces me to specify a concrete dependency. hence all the concrete dependencies have to be resolved at deployment time. Sometimes, this is not feasible. Most of our usecases are based on injecting a particular type based on the runtime data or a message received from an end user.

Most of our design is following command pattern. hence, when we recieve a command, we would like to construct our domain model and based on data received from a command, we inject particular set of types into our aggregate root object. Hence, due to lack of spring's ability to construct a domain model based on runtime data, we are forced to use static factory methods, builders and Factory patterns.

Can someone please advise if spring has a problem to the above scenario ?

I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure.

like image 762
Jimm Avatar asked Sep 17 '09 16:09

Jimm


1 Answers

I suggest you read the section in the Spring docs concerning Using AspectJ to dependency inject domain objects with Spring.

It's interesting that you said "I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure, " considering that AOP is a core part of Spring's infrastructure. The two go very well together.

The above link allows you to have Spring's AOP transparently inject dependencies into domain objects that are creating without direct reference to the Spring infrastructure (e.g. using the new operator). It's very clever, but does require some deep-level classloading tinkering.

like image 140
skaffman Avatar answered Oct 30 '22 04:10

skaffman