問題:
生成的ws(webservice)客戶端代碼,wsdl的文件地址寫死在文件中,無法從配置中心讀取。
步驟:
查看地址寫死位置
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://xx.xxx.xx.xxx:8001/soa-infra/services/HOL/HOL_M02_PageInquiryParentCompanyInfoSrv/HOL_M02_PageInquiryParentCompanyInfoSrv_ep?WSDL");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
HOLM02PAGEINQUIRYPARENTCOMPANYINFOSRVEP_WSDL_LOCATION = url;
HOLM02PAGEINQUIRYPARENTCOMPANYINFOSRVEP_EXCEPTION = e;
}
靜態代碼塊中的變量注入
由於靜態代碼塊會先於spring注入執行,故常規思路不可行。
創建配置文件schedule.properties,和配置類ScheduleHrConfig。配置填寫在schedule.properties中。
@Configuration
@PropertySource("classpath:schedule.properties")
@EnableCaching
public class ScheduleHrConfig
{
@Value("${hr.sync.dept.wsdl}")
private String deptWsdl;
public String getDeptWsdl()
{
return deptWsdl;
}
public void setDeptWsdl(String deptWsdl)
{
this.deptWsdl = deptWsdl;
}
}
靜態注入之前,先實現 spring 的一個獲取上下文的工具類
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring工具類,獲取Spring上下文對象等
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringContextUtil.applicationContext == null){
SpringContextUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
靜態注入:
static {
URL url = null;
WebServiceException e = null;
try {
//url = new URL("http://soa.zte.com.cn:8001/soa-infra/services/HOL/HOL_M02_PageInquiryParentCompanyInfoSrv/HOL_M02_PageInquiryParentCompanyInfoSrv_ep?WSDL");
ScheduleHrConfig config = (ScheduleHrConfig)SpringContextUtil.getBean("scheduleHrConfig", ScheduleHrConfig.class);
url = new URL(config.getDeptWsdl());
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
HOLM02PAGEINQUIRYPARENTCOMPANYINFOSRVEP_WSDL_LOCATION = url;
HOLM02PAGEINQUIRYPARENTCOMPANYINFOSRVEP_EXCEPTION = e;
}
當然要在EP類加上@component,在調用的時候不再使用new,而是使用spring注入。
然后就可從配置中心獲取值了。
