简体   繁体   中英

Is there any standard Java dependency injection API based on static context?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM