这个问题,网上有很多解决方案,我采用的是如下这种最简单的解决方案,直接上代码:
package com.steven.schedule;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
/**
* @author Steven
* @date 2019年8月20日
*/
@Component
public class TaskSchedulePropertiesRefresher implements ApplicationContextAware {
private static Logger logger = Logger.getLogger(TaskSchedulePropertiesRefresher.class);
private ApplicationContext applicationContext;
@ApolloConfigChangeListener
public void onChange(ConfigChangeEvent changeEvent) {
refreshTaskScheduleProperties(changeEvent);
}
private void refreshTaskScheduleProperties(ConfigChangeEvent changeEvent) {
logger.info("Refreshing TaskSchedule properties!");
// 更新相应的bean的属性值,主要是存在@ConfigurationProperties注解的bean
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
logger.info("TaskSchedule properties refreshed!");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}