spring中使用@PostConstruct注解,完成静态对象注入

为什么static对象不可直接使用@Autowired注入?

Spring/SpringBoot正常情况下不能支持注入静态属性(会报空指针异常)。主要原因在于:Spring的依赖注入实际上是使用Object.Set()进行注入的,Spring是基于对象层面的依赖注入,而静态属性/静态变量实际上是属于类的。

@PostConstruct和@PreDestroy

@PostConstruct 为JavaEE5规范开始后Servlet中新增@PostConstruct和@PreDestroy
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。
@PostConstruct 在构造函数之后执行,init()方法之前执行。
@PreDestroy()方法在destroy()方法之后执行

执行顺序:Constructor >> @Autowired >> @PostConstruct

使用示例

package com.sijing.codeRecord.httpUtil;



import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

@Component
public class HttpStaticUtil {
	
	@Autowired
	RestTemplate restTemplate;
	
	private static RestTemplate staticRestTemplate;
	
	@SuppressWarnings("static-access")
	@PostConstruct
	public void staticVarAssignment() {
		this.staticRestTemplate = restTemplate;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void Post() {
		HttpEntity requestEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.valueOf("application/json"));
		requestEntity = new HttpEntity(String.format(""), headers);
		JSONObject response = staticRestTemplate.postForObject("http://www.baidu.com", requestEntity, JSONObject.class);
		System.out.println(response);
	}
	
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值