0

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.

Nageswara Rao
  • 954
  • 1
  • 10
  • 32
  • 1
    Which java version you're using? – Premraj Sep 13 '12 at 12:12
  • This link below possibly answers your question. http://www.theserverside.com/news/1321158/A-beginners-guide-to-Dependency-Injection Thanks –  Sep 13 '12 at 12:12

4 Answers4

3

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.

Premraj
  • 7,802
  • 8
  • 45
  • 66
2

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.

Hearen
  • 7,420
  • 4
  • 53
  • 63
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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

Community
  • 1
  • 1
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

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

Perkone
  • 57
  • 3
  • 8
Nageswara Rao
  • 954
  • 1
  • 10
  • 32
  • You should add link to your solution if you did it on your own otherwise the purpose of this topic and your question is remained unfulfilled! – pratapvaibhav19 Jul 19 '18 at 09:33