Spring使用@Resource、@Autowired注入时出现空指针问题的原因
http://blog.csdn.net/yzj99848873/article/details/45012193
举例说明:
这是一个类,使用了@Component注解,里面有两个依赖注入的属性,使用@Autowired注解.
package cn.yearcon.shop.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class HttpClientUtil {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;
/**
* 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 调用不带参数的get请求
return this.doGet(uriBuilder.build().toString());
}
/**
* 带参数的post请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 构造from表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表单放到post里
httpPost.setEntity(urlEncodedFormEntity);
}
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
response.getEntity(), "UTF-8"));
}
/**
* 不带参数post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
return this.doPost(url, null);
}
}
现在,我们要使用上面的类,
package cn.yearcon.shop.controller;
import cn.yearcon.shop.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
@RestController
public class Weixin {
@Value("${weixin.appid}")
String appid ;
@Value("${weixin.secret}")
String secret;
@Value("${weixin.grant_type}")
String grant_type;
@RequestMapping(value = {"shop", ""})
public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 用户同意授权后,能获取到code
String code = request.getParameter("code");
System.out.println("===code==" + code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
HashMap<String, Object> map = new HashMap<String, Object>(16);
map.put("appid",appid);
map.put("secret",secret);
map.put("grant_type",grant_type);
map.put("code",code);
HttpClientUtil httpClientUtil = new HttpClientUtil();
String body = httpClientUtil.doGet(url, map);
System.out.println(body);
return "hello";
}
}
注意,HttpClientUtil 是我们手动new出来的,不是使用Spring自动装配进来的.
这时候运行就会出现 空指针异常,
追查原因是因为: HTTPclientUtil 类的
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;
这两个属性都是null,也就是没注入进来,既然是空,那调用它们的方法自然会产生空指针异常.
Spring java配置及注解注入方法出现空指针异常的原因
当通过new的方式创建一个对象的时候,虽然期望使用了注解@Autowired对这个对象进行装配,但是Spring是不会这么做的,因为Spring不会对任意一个new 出来的对象进行自动装配,只有这个对象也是一个在Spring中注册过的Bean,才会获得自动装配的功能。
使用Spring注入HttpClientUtil
package cn.yearcon.shop.controller;
import cn.yearcon.shop.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
@RestController
public class Weixin {
@Autowired
private HttpClientUtil httpClientUtil;
@Value("${weixin.appid}")
String appid ;
@Value("${weixin.secret}")
String secret;
@Value("${weixin.grant_type}")
String grant_type;
@RequestMapping(value = {"shop", ""})
public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 用户同意授权后,能获取到code
String code = request.getParameter("code");
System.out.println("===code==" + code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
HashMap<String, Object> map = new HashMap<String, Object>(16);
map.put("appid",appid);
map.put("secret",secret);
map.put("grant_type",grant_type);
map.put("code",code);
String body = httpClientUtil.doGet(url, map);
System.out.println(body);
return "hello";
}
}
这样我们让Spring来给我们注入HttpClientUtil示例,那么它里面的其他使用@Autowired 注解的属性,Spring才会帮助我们都注入进来