我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象。如果这是spring框架的独立应用程序,我们通过
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
这样的方式就可以很轻易的获取我们所需要的对象。
但是往往我们所做的都是Web Application,这时我们启动spring容器是通过在web.xml文件中配置,这样就不适合使用上面的方式在普通类去获取对象了,因为这样做就相当于加载了两次spring容器,而我们想是否可以通过在启动web服务器的时候,就把Application放在某一个类中,我们通过这个类在获取,这样就可以在普通类获取spring bean对象了,让我们接着往下看
普通类调用Spring bean对象:
这里有更多这方面的介绍,比较详细
下面介绍在springboot中是如何使用的
1.在Spring Boot可以扫描的包下
写的工具类为SpringUtil,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean
springutil:
packageme.shijunjie.util;importorg.springframework.beans.BeansException;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;importorg.springframework.stereotype.Component;
@Componentpublic class SpringUtil implementsApplicationContextAware {private staticApplicationContext applicationContext;
@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throwsBeansException {if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext=applicationContext;
}
System.out.println("--------------------------------------------------------------------