new对象如何使用 @mapper或者 @service

需求

定时任务中注册task
在这里插入图片描述
这里如果直接使用
@Autowired
DynamicPrintTask task;
这个task的话 因为设置的是单例的 所以 不管你加多少 task 他永远只会以最后一个task 来执行所有的任务
所以这里需要用 new的形式来创建 task
在这里插入图片描述
但是这个task 里面 用到了 很多 mapper 如果直接 用 new 的话 这些mapper 则会报 null
所以我们需要通过 ApplicationContext 来获取上下文

解决方案

public class SpringContextUtil {
    private static ApplicationContext applicationContext;

    //获取上下文
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //设置上下文
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //通过名字获取上下文中的bean
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

    //通过类型获取上下文中的bean
    public static Object getBean(Class<?> requiredType){
        return applicationContext.getBean(requiredType);
    }
}
public class WebApplication {
	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(WebApplication.class, args);
		SpringContextUtil.setApplicationContext(context);

	}

}

错误使用springbean

//    @Autowired
//    SpringScheduledCronMapper springScheduledCronRepository;
//
//    @Autowired
//    ReportModulMapper reportModulMapper;
//
//    @Autowired
//    TemplateAssemblyMapper templateAssemblyMapper;
//
//    @Autowired
//    VulnerabilityDataAnalysisService vulnerabilityDataAnalysisService;
//
//    @Autowired
//    ReportAssemblyMapper reportAssemblyMapper;
//
//    @Autowired
//    SafetyIncidentHandlingService safetyIncidentHandlingService;
//
//    @Autowired
//    ReportRecordMapper reportRecordMapper;
//

正确使用

  ReportModulMapper reportModulMapper = (ReportModulMapper) SpringContextUtil.getBean(ReportModulMapper.class);
        TemplateAssemblyMapper templateAssemblyMapper = (TemplateAssemblyMapper)SpringContextUtil.getBean(TemplateAssemblyMapper.class);
        VulnerabilityDataAnalysisService vulnerabilityDataAnalysisService = (VulnerabilityDataAnalysisService)SpringContextUtil.getBean(VulnerabilityDataAnalysisService.class);
        ReportAssemblyMapper reportAssemblyMapper= (ReportAssemblyMapper)SpringContextUtil.getBean(ReportAssemblyMapper.class);
        SafetyIncidentHandlingService safetyIncidentHandlingService = (SafetyIncidentHandlingService)SpringContextUtil.getBean(SafetyIncidentHandlingService.class);
        ReportRecordMapper reportRecordMapper =(ReportRecordMapper)SpringContextUtil.getBean(ReportRecordMapper.class);

原因

@Autowired 是获取springioc容器里面的对象 而 通过 new 的形式 是 不能 获取到的 所以 需要通过ApplicationContext 获取上下午 获取到 bean对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值