Nageswara Rao
Nageswara Rao

Reputation: 964

DI and IOC using core java

Is there a way to use core java/reflection to load create dependency objects and set it to other as a dependency?

I could do it, but the facing issues while dealing with nested beans.

Ultimately, I am not interested to use spring for the simple usage.

Any help much appreciated.

Upvotes: 0

Views: 1697

Answers (4)

Nageswara Rao
Nageswara Rao

Reputation: 964

I have written it myself.

Couple of pre-requisites though

  1. Format your xml to reduce the load on parser. I have defined xml element <bean id="xyz" class="package path of class"> for declaring a class, and <parameter name="xyz" value="val"> or <parameter name="xyz" ref="beanid"> for instance variables. Parameter can point to a value or reference of another object
  2. On the parser side, all beans are created using reflection and posted into hashmap, from there dependency can be injected using parameters either by reference or by value

Pretty simple. Thanks for all comments

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

You don't need a framework to use DI.

You can

  • create all objects e.g. with new
  • passing via a constructor all mandatory objects/arguments.
  • pass optional arguments via setters.
  • pass objects which can only be constructed later via setters.

You can write your own IoC to do this as well, but writing it in Java is likely to be best if you want simplicity.

BTW: If you want runtime loading, you can compile and load Java code at runtime if you need to.

Upvotes: 2

Mark Bramnik
Mark Bramnik

Reputation: 42491

I wouldn't reinvent the wheel here, possible you should take a light weight dependency injection container.

Probably this post will help you to make a choice: DI containers

Hope this helps

Upvotes: 1

Premraj
Premraj

Reputation: 7902

I would recommend not to do it manually, its hard to get it correct and why to reinvent the wheel when there are plenty of solutions already exists? -
Dependency injection specification for java is JSR-299 and you can use Weld library as an reference implementation if you don't want to use Spring
You can consider Guice framework as well , its a lightweight DI framework.

Upvotes: 3

Related Questions