场景:部分接口需要包装成SDK对外暴露,SDK需要获取外部项目的配置文件来判断是否重试以及打印日志等情况。
1.在SDK中添加配置类SpringContextHolder
import org.apache.http.util.Asserts;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
assertApplicationContext();
return SpringContextHolder.applicationContext;
}
public static <T> T getBean(String beanName){
assertApplicationContext();
return (T)SpringContextHolder.applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> typeName){
assertApplicationContext();
return applicationContext.getBean(typeName);
}
private static void assertApplicationContext(){
Asserts.notNull(applicationContext, "applicationContext");
}
}
2.在SDK中获取外部项目中配置的是否开启日志参数,如果外部项目不配置该参数,默认不打印。
/**
* 设置是否打印日志
* @return
*/
public static Boolean getLogFlag() {
String flag = SpringContextHolder.getApplicationContext().getEnvironment().getProperty("enable-log");
if (org.apache.commons.lang3.StringUtils.isBlank(flag)) {
return false;
}
try {
return Boolean.valueOf(flag);
} catch (Exception e) {
return false;
}
}
3.外部项目引入SDK依赖后,需要在启动类添加注解@Import(SpringContextHolder.class)
通过上述操作,外部项目配置SDK所需参数后,SDK可以通过环境变量判断是否打印日志。