• 多线程时Autowired自动注入问题


    在多线程时使用@Autowired总是获取不到bean,原因是:new thread不在spring容器中,也就无法获得spring中的bean对象。

    解决方法:手动获取

    package com.zuikc.web.controller;

    import com.zuikc.dao.user.bean.User;
    import com.zuikc.dao.user.mappers.IUserMapper;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    import java.util.List;

    @Controller
    @RequestMapping("/app")
    public class GetApplicationController implements ApplicationContextAware {

    private static ApplicationContext applicationContext;//springMVC上下文定义
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    GetApplicationController.applicationContext=applicationContext;
    }
    public static ApplicationContext getApplicationContext(){
    return GetApplicationController.applicationContext;
    }
    public static<T> T getBean(String name)throws BeansException{
    return (T)applicationContext.getBean(name);
    }

    @RequestMapping("getapp")
    public String GetAPP(){
    IUserMapper userMapper = applicationContext.getBean(IUserMapper.class);
    List<User> list = userMapper.GetAll();

    String a="11";
    return "hello";
    /*SpringApplicationContext.getApplicationContext().getBean(CategoryMapper.class)*/
    }

    }

      

     

      

      

    
    



    在其他service里调用

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("upFinancial-pool-%d").build();
                ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                        6000L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingDeque<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
                UpFinancialContractHandler handler=new UpFinancialContractHandler();
                handler.setUser(user);
                pool.execute(handler);
    

      

  • 相关阅读:
    20169306《网络攻击与防范》第八周学习总结
    20169306《网络攻击与防范》第七周学习总结
    20169306《网络攻击与防范》第六周学习总结
    20169306《网络攻击与防范》第五周学习总结
    20169306《网络攻击与防范》第四周学习总结
    SQL注入
    路径遍历漏洞
    sqlmap安装及简单使用——12.30
    margin,CSS边距重叠
    20169314 2016-2017-2《网络攻防》课程总结
  • 原文地址:https://www.cnblogs.com/albertzhangyu/p/9648576.html
Copyright © 2020-2023  润新知