1.通过实现ApplicationContextAware 接口来实现在Springboot 启动时加载这个类,并把上下文对象注入
package com.cfcc.bigdata.common.spring;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring 工具类 ,获取Spring容器中的上下文信息
* 使用的时候需要注入到 springmvc-config.xml 如下设置:
*/
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return context;
}
/**
* 根据bean的类型获取IOC中的bean 对象
*/
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
return context.getBean(clazz);
}
/**
* 根据bean名称获取IOC中的bean 对象
*/
public static <T> T getBean(String beanName) {
checkApplicationContext();
return (T)context.getBean(beanName);
}
public void setApplicationContext(ApplicationContext ac) throws BeansException {
context = ac;
}
private static void checkApplicationContext() {
if (context == null) {
throw new RuntimeException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
}
2.在Springboot的启动类中,将spring的工具类注入到IOC容器中
package com.cfcc.bigdata;
import com.cfcc.bigdata.client.context.RegisterContext;
import com.cfcc.bigdata.common.spring.SpringContextHolder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import javax.annotation.Resource;
//首先要将spring boot自带的DataSourceAutoConfiguration禁掉,因为它会读取application.properties文件的spring.datasource.*属性并自动配置单数据源。在@SpringBootApplication注解中添加exclude属性即可:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableTransactionManagement
public class TeisAuthApplication {
public static void main(String[] args) {
SpringApplication.run(TeisAuthApplication.class, args);
}
/**
* Spring工具类
* @return
*/
@Bean(name ="springContextHolder")
public SpringContextHolder getSpringContextHolderBean() {
return new SpringContextHolder();
}
}