【Java Web】从配置修改静态变量
对象
@ConfigurationProperties(prefix = "system-upload-prefix")
@Configuration
@RefreshScope
@Data
public class SystemUploadPrefix {
private String upload;
}
修改常量
@Component
public class Constants {
@Autowired
SystemUploadPrefix systemUploadPrefix;
@PostConstruct
public void loadSystemUploadPrefix() {
UPLOAD_DEFAULT_PREFIX_URL = systemUploadPrefix.getUpload();
}
public static String UPLOAD_DEFAULT_PREFIX_URL = "/upload/";
}
nacos修改后刷新
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigChangeEvent;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import com.deyatech.common.Constants;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class NacosConfigListener extends AbstractConfigChangeListener implements InitializingBean {
@Resource
private NacosConfigManager nacosConfigManager;
@Override
public void afterPropertiesSet() throws Exception {
nacosConfigManager.getConfigService().addListener("global.yaml", "DEFAULT_GROUP", this);
}
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
for (ConfigChangeItem changeItem : event.getChangeItems()) {
String value = changeItem.getNewValue();
String key = changeItem.getKey();
if (key.equals("system-upload-prefix.upload")) {
Constants.UPLOAD_DEFAULT_PREFIX_URL = value;
System.out.println("Listener UPLOAD_DEFAULT_PREFIX_URL -> " + Constants.UPLOAD_DEFAULT_PREFIX_URL);
}
if (key.equals("system-upload-prefix.secureAqMl")) {
Constants.UPLOAD_SECURE_PREFIX_URL = value;
System.out.println("Listener UPLOAD_SECURE_PREFIX_URL -> " + Constants.UPLOAD_SECURE_PREFIX_URL);
}
if (key.equals("system-upload-prefix.sourceMaterial")) {
Constants.UPLOAD_SOURCE_MATERIAL_URL = value;
System.out.println("Listener UPLOAD_SOURCE_MATERIAL_URL -> " + Constants.UPLOAD_SOURCE_MATERIAL_URL);
}
}
}
}