java使用线程时注入SpringBoot接口
1. 编写多线程注入方法工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
/**
* 多线程注入方法,工具类
* @Author my.guo
*/
@Configuration
public class SpringBeanUtil implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
/**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
/**
* 通过name获取 Bean.
* @return
*/
public static Object getBean(String name) {
if (applicationContext == null){
throw new RuntimeException("applicationContext注入失败");
}
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
* @return
*/
public static <T> T getBean(Class<T> type) {
if (applicationContext == null){
throw new RuntimeException("applicationContext注入失败");
}
return getApplicationContext().getBean(type);
}
/**
* 通过name,以及Clazz返回指定的Bean
* @return
*/
public static <T> T getBean(String name, Class<T> type) {
if (applicationContext == null){
throw new RuntimeException("applicationContext注入失败");
}
return getApplicationContext().getBean(name, type);
}
}
2. 构造函数注入接口
public class UploadThread implements Runnable{
private SqlConfig sqlConfig;
private ServiceApiService serviceApiService;
public UploadThread(){
this.sqlConfig = SpringBeanUtil.getBean(SqlConfig.class);
this.serviceApiService = SpringBeanUtil.getBean(ServiceApiService.class);
}
@SneakyThrows
@Override
public void run() {
}
}