0

Without depending from third-party frameworks, I would like to have a static context class to inject dependencies across different packages of my application. This way, I could avoid to pass the reference to a context object through several calls.

I have been looking at the standard Java APIs and found out about the javax.naming.Context interface and its implementation javax.naming.InitialContext. These can be used for dependency injection, but the context object would be non-static.

Basically, I would like to set a reference to an object from one package and get the same reference from another one. In other words, I would have a similar call in class (or package) A:

MyContext.setInstanceOf(MyInterface.class, new MyInterfaceImpl());

And the corresponding call in class (or package) B:

MyInterface obj = (MyInterface) MyContext.getInstanceOf(MyInterface.class);

Thanks.

aviola
  • 3
  • 3
  • 1
    AFAIK no. Rolling your own static method should do the trick – Thiyagu Jan 21 '20 at 16:53
  • Have you considered making your own context class, using [the singleton design pattern](https://www.callicoder.com/java-singleton-design-pattern-example/)? – Green Cloak Guy Jan 21 '20 at 16:53
  • Singleton is a bit of an anti pattern. If you really don't want to use a library (google guice) You can roll your own with only the java collections Map/HashTable provided you only need singleton scope and your dependencies don't contain cycles (Or you are willing to use setter based injection). – Keynan Jan 21 '20 at 16:57
  • @GreenCloakGuy Indeed, I also was thinking about making it a singleton. But first, I would avoid re-inventing the wheel if Java already provides a standard way. – aviola Jan 21 '20 at 17:01
  • @Keynan InitialContext already relies on hash tables. However, this way I would be obliged to pass the Map/HashTable/InitialContext object to whathever class needs it. – aviola Jan 21 '20 at 17:07

1 Answers1

0

In Scala I used the cake pattern I think that this is very pure and easy without a framework.

Because of the lack of traits in Java it is not so easiely applied to Java, but this SO Question and this blogpost have examples implementing the cake pattern in Java 8.

Perhaps you give it a try.

thopaw
  • 3,796
  • 2
  • 17
  • 24