Spring获取当前ApplicationContext

130

我正在使用Spring MVC框架开发我的Web应用程序。我的bean是在"spring-servlet.xml"文件中编写的。

现在我有一个名为MyClass的类,我想使用Spring Bean来访问这个类。

spring-servlet.xml文件中,我已经编写了以下内容:

TBD

<bean id="myClass" class="com.lynas.MyClass" />

现在我需要使用 ApplicationContext 来访问它。

ApplicationContext context = ??

以便我能够做到

MyClass myClass = (MyClass) context.getBean("myClass");

如何做到这一点??


3
@Autowired MyClass myClass应该能胜任这个工作! - Mannekenpix
12个回答

0

比使用@Autowired更好的是通过构造函数注入它。在这里找到一些支持构造函数注入的理由。

@Component
public class MyClass{
  private final ApplicationContext applicationContext;

  public MyClass(ApplicationContext applicationContext){
    this.applicationContext = applicationContext;
  }

  //here will be your methods using the applicationcontext
}

0
如果你的 main() 方法中有 SpringApplication.run() 方法,那么你应该记住它默认会返回 ApplicationContext 对象。详见 this。也就是说,你可以这样做:
ApplicationContext context=SpringApplication.run(YourMainMethodClassName.class,args);
MyClass obj=(MyClass)context.getBean(MyClass.class);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接