0

How to instantiate java class with parameters and use the same instance through out the application?

What i want to do is when a tibco esb requests a web service call to my application,i will capture user information(user name) in one pojo class so that I can use this pojo class and user information at other places in application also for this particular tibco request.

This question might sounds crazy but I would like to implement something like this in my application.Waiting for your thoughts guys.

Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50
Vikas Chowdhury
  • 737
  • 8
  • 15

1 Answers1

1

You can use a ThreadLocal solution:

public class MyClassInstanceHolder {
    private static ThreadLocal<MyClass> instance = new ThreadLocal<>();

    public static setInstance(MyClass instance) {
        instance.set(instance);
    }
    public static MyClass getInstance() {
        instance.get();
    }
}
...
MyClass myInstance = MyClassInstanceHolder.getInstance();

So in that thread you'll have access to the object stored in that ThreadLocal.

Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50
  • For the above solution,should i need to call or depend upon OtherClass everytime?I mean if i like to use MyClass instance in some other class then i would need to instantiate OtherClass also(WebServiceImpl class in my case)? – Vikas Chowdhury Aug 25 '15 at 11:22
  • Well, not, it's only an example I've done fast. You could have two static methods, one for set another for get, so you don't need to instantiate the class. I'm going to update the example. – Eduardo Yáñez Parareda Aug 25 '15 at 13:34