原理
静态变量在静态代码块加载后加载,且注解也在之后加载,完成动态注入修改注解里的参数
示例
1、下面例子是在springboot项目下写的,项目中包含application-xxx.properties的不同环境的配置文件,配置文件中包含com.pay.url=http://···
属性,需要在项目启动时赋值给代码中的WSDLURL
常量,和@WebServiceClient
的wsdlLocation
属性;
2、下面代码中的静态变量WSDLURL
是在static{}
代码块中初始化的,常量WSDL_LOCATION
也可以用同样的方法初始化,但常量要保证赋值且只赋值一次。
@WebServiceClient(name = "SLEWebService",
wsdlLocation = "${WSDLURL}",
targetNamespace = "http://tempuri.org/")
public class SLEWebService_Service extends Service {
//静态变量在静态代码块加载后加载,且注解也在之后加载,完成动态注入修改注解里的参数
public static String WSDLURL;
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://tempuri.org/", "SLEWebService");
public final static QName SLEWebServiceSoap = new QName("http://tempuri.org/", "SLEWebServiceSoap");
static {
Properties properties;
try {
Environment environment = ApplicationContextUtil.getBean(Environment.class);
String[] profiles = environment.getActiveProfiles();
properties =
//如果启动用的文件是application-dev.properties, 则profiles[0]="dev"
PropertiesLoaderUtils.loadAllProperties("application-" + profiles[0] + ".properties");
//遍历取值
Set<Object> objects = properties.keySet();
for (Object object : objects) {
//取到参数赋值给静态变量
if (object.toString().equals("com.pay.url")) {
WSDLURL = new String(properties.getProperty((String) object).getBytes("iso-8859-1"), "gbk");
}
}
} catch (IOException e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(WSDLURL);
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(SLEWebService_Service.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "file:/D:/ztest-workspace/SLEWebService.xml");
}
WSDL_LOCATION = url;
}
ApplicationContextUtil.java
package com.jidanchang.comm.util;
/*
* Copyright (C), 2010-2020, 鸡蛋肠
* FileName: ApplicationContextUtil
* @author : 鸡蛋肠
* Date: 2020/12/14 15:13
* Description: 手动获取bean工具类
*/
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* ClassName ApplicationContextUtil
* Description 手动获取bean工具类
*
* @author 鸡蛋肠
* @date 2020/12/14 15:13
*/
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
/**
* 声明一个静态变量保存
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext=applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
}