如果直接用spring注入靜態屬性,則會報錯,提示@Resource annotation is not supported on static fields,如果又一定要通過spring注入bean,可以採用@PostConstruct註解在某個用來初始化的方法上,注入時注入到另一個不是靜態的變量裏,然後在初始化方法裏面將注入好的變量賦值給靜態變量,通過這些操作就給靜態變量賦值。
package com.inth.base.util;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.inth.service.core.cache.RedisCacheService;
/**
* 編號生成器
* <P>File name : CodeGenerator.java </P>
* <P>Author : DingYinLong </P>
* <P>Date : Jul 15, 2014 </P>
*/
@Component
public class CodeGenerator {
@Resource
private RedisCacheService redisCacheService;
public static RedisCacheService redisService;
//通過該標籤以及該方法實現給static屬性注入
@PostConstruct
public void init(){
CodeGenerator.redisService = redisCacheService;
}
/**
* 通過編號前綴以及編號值生成編號
* CodeGenerator.generate()<BR>
* <P>Author : DingYinLong </P>
* <P>Date : Jul 15, 2014 </P>
* @param code
* @param num
* @return
*/
public static String generate(String code,String num){
for (int i = code.length()+num.length(); i < Constans.CODE_LENGTH; i++) {
code += "0";
}
return code + num;
}
/**
* 用redis生成編碼
* CodeGenerator.getRedisCode()<BR>
* <P>Author : DingYinLong </P>
* <P>Date : Jul 21, 2014 </P>
* @param code
* @return
*/
public static String getRedisCode(String code){
synchronized (code) {
Object num = redisService.get(code);
if(num == null){
redisService.persist(code, 1);
num = 1;
}
redisService.persist(code, (Integer)num + 1);
String str = generate(code, String.valueOf(num));
return str;
}
}
}
源代碼的用途是利用redis來生成唯一有規律的編碼