@Autowired注入配置类报控制针异常

监听类注入配置文件报空指针异常

问题1.需要将线程池的参数抽取到yml文件里进行设置,然后读取yml中配置
问题2. 在监听类,或定时任务 中需要操作数据库service,mapper,或者读取配置文件中的配置,无法注入报空指针,无论是@autowired还是@component,此时需要自己手动获取bean对象实现,这样的场景比较常见。有两种方法可以获取到

方法一

实现ApplicationContextAware方法,通过 applicationContext.getBean(TsReservationService.class)方法获取需要注入的bean
场景:需要获取Service层的bean去实现业务逻辑处理

import org.springframework.context.ApplicationContextAware;

@Component
public class FindJob implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Scheduled(fixedDelay = 1000 * 60)
    public void find() {
        System.out.println("查询符合数据任务开启!^_^");
        //获得对应需求 Bean
        applicationContext = FindJob.getApplicationContext();
        TsReservationService tsReservationService = applicationContext.getBean(TsReservationService.class);
        TaskService taskService = applicationContext.getBean(TaskService.class);
        }
方法二

使用注解 @PostConstruct
场景:需要将配置文件application.properties中的配置读取到监听类中


@Component
public class InjectUtil {

    @Autowired
    public PDFConfig config;//这个就是需要读取进来的配置项
    
    private InjectUtil (){}
    
    @PostConstruct
    public void init(){
        InjectUtil.getInstance().config = this.config;
    }

    private static class SingletonHolder {
        private static final InjectUtil INSTANCE = new InjectUtil();
    }

    public static final InjectUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public PDFConfig getConfig(){
        return InjectUtil.getInstance().config;
    }
}

在监听类中使用的时候就可以通过工具包injectUtil来获取PDFConfig这个配置

@Component
public class PDFBuilder extends PdfPageEventHelper {
	 //加分页
        public void addPage(PdfWriter writer, Document document) throws IOException, DocumentException {
			 PDFConfig config = InjectUtil.getInstance().config;//这样就不会报控制针了
			 }
 }

版权声明:本文为biu_biu_duda原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。