spring boot 给静态变量注入值

###问题:
application.properties中配置下面两个配置项
ccb.ip.address=10.25.177.31
ccb.ip.port=1600
下面问题代码中读取不到application.properties配置文件中的配置

###问题代码:

public class BISFrontFileUtil {
	private static Logger logger = LoggerFactory.getLogger(BISFrontFileUtil.class);
	@Value("${ccb.ip.address}")
	private static String CCBIPADDRESS;
	@Value("${ccb.ip.port}")
	private static int CCBIPPORT;
	
	public static boolean putFileToFront(String fileName, String fileContentStr) {
		boolean flag = false;
		try {
			String clientFlag = "in"; 
			logger.info("文件名:" + fileName + ",IP地址:" + CCBIPADDRESS + ",端口号:" + CCBIPPORT);
			InputStream in = new ByteArrayInputStream(fileContentStr.getBytes("UTF-8"));
			ResultBean result = BankFileHandleServiceImp.sendBankStream(in,
					fileContentStr.getBytes().length, fileName, CCBIPADDRESS, CCBIPPORT, clientFlag);
			String resultCode = result.getPA_RSLT_CODE();// 获取上传的结果
			String resultMsg = result.getPA_RSLT_MESG();
			if (resultCode.equals(ResultCodeUtil.CODE_999999)) {// 999999表示上传成功
				logger.info("上传文件" + fileName + "成功");
				flag = true;
			} else {
				logger.info("上文件失败,失败代码:" + resultCode + ",失败信息:" + resultMsg);
			}
		} catch (Exception e) {
			logger.error("异常", e);
		}
		return flag;
	}
}

###结果:
运行后发现CCBIPADDRESS为null ,CCBIPPORT为0(int默认为0了)。

###原因:
后来google发现spring boot不允许/不支持把值注入到静态变量中。

###修正方法:
spring boot支持set方法注入,我们可以利用非静态set方法注入静态变量

###修正代码:


@Component
public class BISFrontFileUtil {
	private static Logger logger = LoggerFactory.getLogger(BISFrontFileUtil.class);

	private static String CCBIPADDRESS;

	private static int CCBIPPORT;

	@Value("${ccb.ip.address}")
	public void setCCBIPADDRESS(String cCBIPADDRESS) {
		CCBIPADDRESS = cCBIPADDRESS;
	}

	@Value("${ccb.ip.port}")
	public void setCCBIPPORT(int cCBIPPORT) {
		CCBIPPORT = cCBIPPORT;
	}

	/**
	 * 上传文件至bis前置机
	 * @param fileName
	 * @param fileContentStr
	 * @return
	 */
	public static boolean putFileToFront(String fileName, String fileContentStr) {
		boolean flag = false;
		try {
			String clientFlag = "in"; 
			logger.info("文件名:" + fileName + ",IP地址:" + CCBIPADDRESS + ",端口号:" + CCBIPPORT);
			InputStream in = new ByteArrayInputStream(fileContentStr.getBytes("UTF-8"));
			ResultBean result = BankFileHandleServiceImp.sendBankStream(in,
					fileContentStr.getBytes().length, fileName, CCBIPADDRESS, CCBIPPORT, clientFlag);
			String resultCode = result.getPA_RSLT_CODE();
			String resultMsg = result.getPA_RSLT_MESG();
			if (resultCode.equals(ResultCodeUtil.CODE_999999)) {// 999999表示上传成功
				logger.info("上传文件" + fileName + "成功");
				flag = true;
			} else {
				logger.info("上传文件失败,失败代码:" + resultCode + ",失败信息:" + resultMsg);
			}
		} catch (Exception e) {
			logger.error("异常", e);
		}
		return flag;
	}
}

###注意:
1、 修正代码中的@Component不可丢掉了
2、 set方法要是非静态的

你可能感兴趣的:(spring,boot,java,spring)