栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线程中使用@Autowired注入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程中使用@Autowired注入

线程中使用@Autowired注入
  • 场景
  • 工具RestTemplate
    • 代码实现

场景

多多线程同时访问接口,测试接口稳定性

工具RestTemplate

使用springboot自带http调用
线程类实现Callable

代码实现

一下是通过@Autowired注入的方式

public static void main(String[] arge){
            Future p = pool.submit(new RunnableUtil(url, urlSuffixInsertNews, body1, tokenDto.getToken()));
            JSONObject resJson = JSONObject.parseObject(p.get().toString());
}

线程类

package com.yx.util.runnable;

import com.alibaba.fastjson.JSONObject;
import com.yx.util.httpClient.ClientUtil;
import lombok.Data;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Data
public class RunnableUtil implements Callable {

	@Autowired
    private ClientUtil clientUtil;
    
    private String url;
    private Map json;
    private String urlSuffix;
    private String token;
    public RunnableUtil(String url, String urlSuffix, Map json, String token){
        super();
        this.url = url;
        this.urlSuffix = urlSuffix;
        this.json = json;
        this.token = token;
    }
    @Override
    public Object call() throws Exception {
        String res = clientUtil.doPost(url, urlSuffix, json, token);
        return res;
    }
}

请求方法

package com.yx.util.httpClient;


import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;

import java.util.Map;
@Component
public class ClientUtil {

	 @Autowired
    private RestTemplate restTemplate;
    
    public static String doPost(String url, String urlSuffix, Map body, String token){

        DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(url);
        factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES);
        restTemplate.setUriTemplateHandler(factory);
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);

        HttpEntity requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(urlSuffix,requestEntity , String.class);
        if(responseEntity.getStatusCode().is2xxSuccessful()){
            System.out.println(responseEntity.getBody());
        }else {
            System.out.println(responseEntity.getStatusCode().value()+ "和" + responseEntity.getBody());
        }
        return responseEntity.getBody();
    }
}

也就是线程@通过Autowired注入的方式调用会一直出现空指针异常
解决方案就是在晚上找一个获取bean的方法

@Component
public class SpringContextUtil implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
 
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
    
    public static Object getBean(String name) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(name);
    }
 
    
    public static  T getBean(Class clazz) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(clazz);
    }
 
    
    public static  T getBean(String name, Class clazz) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(name, clazz);
    }
}

使用

RestTemplate restTemplate =  SpringContextUtil.getBean(ClientUtil.class)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/590732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号