spring 静态属性的注入技巧


在用@Autowired自动注入属性的时候,如果属性呗声明为静态的,就会注入失败,报空指针异常。

                                          静态注入的技巧

import com.alibaba.fastjson.JSONObject;
import com.rongdu.domain.Rule;
import com.rongdu.service.RuleService;
import com.rongdu.util.StringUtils;

@Component
public class RuleValueType {

	@Autowired
	private RuleService ruleService;

	private static RuleValueType ruleValueType;
	
	@PostConstruct
    public void init(){
		ruleValueType = this;
		ruleValueType.ruleService = this.ruleService;
    }
	
	public static String getRuleCheckValue(String nid,String key ){
		String value = "";
		if(!StringUtils.isBlank(nid)){
			Rule rule = ruleValueType.ruleService.getRuleByNid(nid);
			if(rule!=null){
				JSONObject jsonObject = JSONObject.parseObject(rule.getRuleCheck());
				value = String.valueOf(jsonObject.get(key));
			}
		}
		return value;
	}
}



你可能感兴趣的:(spring)