怎么注销网站/东莞网站推广策划
使用ApplicationContextAware接口的场景
在spring项目中,bean之间的依赖关系是 spring容器自动管理的,但是一个项目中有些类不在spring容器中却需要使用spring管理的bean,这时候不能通过正常的方式(注解等方式)注入bean,在spring中提供了ApplicationContextAware接口,通过ApplicationContextAware接口可以获取到spring上下文,从而从spring上下文中获取到需要的bean。
我们可以编写一个工具类来实现ApplicationContextAware,通过工具类来获取我们需要的bean在spring容器外的类调用bean的方法,具体代码如下:
工具类 SpringUtils.java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;//此处使用注解的方式把工具类加入到容器中,可以使用xml,配置类等方式,必须要加入到容器中
@Component
public class SpringUtils implements ApplicationContextAware {private static ApplicationContext applicationContext; //此方法是父类ApplicationContextAware 中的方法 重写@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtils.applicationContext == null){ SpringUtils.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name){ return getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); }
}
容器外类 TestAppContext.java
public class TestAppContext{//因为Person是容器中的bean TestAppContext不受spring容器管理 所以//这里不能通过正常的方式注入private Person person;public String getPersonName(){//通过bean的名称来获取beanperson = (Person)SpringUtils.getBean("person");return person.getName();}
}
注:这种方式针对的是使用spring管理的web工程,spring容器在项目启动时开始创建,另外也适合Spring Boot的应用程序。