WebService动态地址
1、静态wsdl文件保存在工程中
2、修改文件中接口路径的工具类
public class FileModify {
/**
* 读取文件内容
*
* @param filePath
* @return
*/
public String read(String filePath) {
BufferedReader br = null;
String line = null;
StringBuffer buf = new StringBuffer();
try {
// 根据文件路径创建缓冲输入流
br = new BufferedReader(new FileReader(filePath));
// 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
while ((line = br.readLine()) != null) {
// 此处根据实际需要修改某些行的内容
if (line.startsWith("a")) {
buf.append(line).append(" start with a");
} else if (line.startsWith("b")) {
buf.append(line).append(" start with b");
}
// 如果不用修改, 则按原来的内容回写
else {
buf.append(line);
}
buf.append(System.getProperty("line.separator"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
}
}
}
return buf.toString();
}
/**
* 将内容回写到文件中
*
* @param filePath
* @param content
*/
public void write(String filePath, String content) {
BufferedWriter bw = null;
try {
// 根据文件路径创建缓冲输出流
bw = new BufferedWriter(new FileWriter(filePath));
// 将内容写入文件中
bw.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
bw = null;
}
}
}
}
public void fileAppender(String fileName, String content) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
// 一行一行的读
StringBuilder sb = new StringBuilder();
sb.append(content);
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
reader.close();
// 写回去
RandomAccessFile mm = new RandomAccessFile(fileName, "rw");
mm.writeBytes(sb.toString());
mm.close();
}
/**
* 替换文件
*
* @param address void
*/
public void wr (String address) {
String filePath = FileModify.class.getClassLoader().getResource("wsdl/MdmSubscribeService.wsdl").getPath(); // 文件路径
FileModify obj = new FileModify();
String read = obj.read(filePath);
int f = read.indexOf("location=\"http://");
int fe = read.indexOf("/",f + 19);
String orgAddress = read.substring(f + 10, fe);
String newWsdl = read.replaceAll(orgAddress, address);
obj.write(filePath, newWsdl); // 读取修改文件
}
}
3、配置启动
增加bean实现ApplicationRunner,目的为在容器初始化之后修改wsdl接口地址
@Component
public class APRunner implements ApplicationRunner{
@Value("${auth.webservice.address}")
private String address;
@Override
public void run(ApplicationArguments args) throws Exception {
if (address == null) {
throw new RuntimeException("请配置webservice服务地址参数(auth.webservice.address)");
}
if (address.indexOf("http://") == -1 && address.indexOf("https://") == -1) {
new FileModify().wr("http://".concat(address));
return;
}
new FileModify().wr(address);
}
}
4、项目启动
wsdl地址更换为配置中的地址,实现webService接口地址动态配置