开发者

How can I get access to spring container?

I have a spring container running, and I have class with which I want to have access to the bean created inside spring container. The class I have is not registered with the spring container.

One thing I can do is that I can use MethodInvoker to call a static method, so I will have access to static field (this would be a bean f开发者_StackOverflowrom spring container) in my class always.

Do we have class like WebapplicationContextUtils for a application that is not web?


You can implement ApplicationContextAware


Why don't you provide a static getInstance() method in your Spring-managed bean which allows objects outside of the Spring IOC container to grab an instance of that object? Your Spring managed object most likely will be a singleton so this should work nicely.

For example:

public class MyObj {

  private static instance = null;

  public MyObj() {
    instance = this;
  }

  public static MyObj getInstance() {
    return instance;
  }

}

public class OutsideSpringObj {

  public doSomething() {
    MyObj springManagedObj = MyObj.getInstance();
    if (springManagedObj != null) {
      // do something with spring-managed object
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜