项目场景:
提示:这里简述项目相关背景:
在springboot有关多线程的类里,new出来的线程类中无法使用@Autowired注入Bean,@Autowired注入Spring Bean,则当前类必须也是Spring Bean才能注入成功,不能用new xxx()来获得对象,这种方式获得的对象也无法使用@Autowired注解注入Bean。
因此,当我们在new一个线程之后,发现线程里使用@Autowired注入的对象都是空的,会报空指针异常,不论是构造方法传递实例化还是方法调用都不行,最后有一个解决方法是通过实例类来解决
package com.dareway.micro.servicePhotovoltaics.DealResult;
import java.lang.annotation.Annotation;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class Appzlt implements ApplicationContextAware {
private static ApplicationContext context;
public static <T> T getBean(final Class<T> requiredType) {
return context.getBean(requiredType);
}
public static <T> T getBean(final String beanName) {
@SuppressWarnings("unchecked")
final T bean = (T) context.getBean(beanName);
return bean;
}
public static <T> Map<String, T> getBeans(final Class<T> requiredType) {
return context.getBeansOfType(requiredType);
}
public static Map<String, Object> getBeansWithAnnotation(final Class<? extends Annotation> annotationType) {
return context.getBeansWithAnnotation(annotationType);
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
context = applicationContext;
}
}
private RedisUtils redisUtils = Appzlt.getBean(RedisUtils.class);