springMVC ApplicationContextAware 获取bean
时间: 2024-06-06 17:03:18 浏览: 17
在 SpringMVC 中,ApplicationContextAware 接口是一个回调接口,它的作用是让实现了该接口的类可以方便地获取 Spring 容器中的 Bean。当一个类实现了 ApplicationContextAware 接口后,在该类被初始化时,会自动调用 setApplicationContext 方法,并将 ApplicationContext 对象作为参数传入该方法中。
通过 ApplicationContext 对象,我们可以轻松地获取 Spring 容器中的 Bean,具体代码实现如下:
```java
public class MyBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
private MyOtherBean myOtherBean;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void doSomething() {
// 通过 applicationContext 获取 MyOtherBean 对象
myOtherBean = applicationContext.getBean(MyOtherBean.class);
// 调用 MyOtherBean 的方法
myOtherBean.doSomethingElse();
}
}
```
通过上述代码可以看出,当 MyBean 对象被初始化时,会自动调用 setApplicationContext 方法,并将 ApplicationContext 对象传入该方法中。在 doSomething 方法中,我们可以通过 applicationContext 对象获取 MyOtherBean 对象,并调用其方法。这样,我们就可以在 SpringMVC 中方便地获取 Spring 容器中的 Bean。