背景:使用new方式创建出来的类对象 不能直接通过@Value()注入类中的某些属性,强行注入属性不可用,出现以上问题是因为spring容器管理对应的bean时,无法加载赋值(加载原理–依赖注入方式不同于直接new导致)
解决办法:
提供一个构造方法对属性进行赋值,如下:
@Slf4j
@Configuration
public class XxxxDataTemplate {
@Value("#{${processing.pyUrl.setting:{}}}")
private Map<String,String> urlMap;
public Map<String,String> getUrlMap(){
return urlMap;
}
}
@Slf4j
@Component
public class MQContext {
@Resource
private XxxxDataTemplate xxxxDataTemplate;
public XxxxDataTemplate getXxxxDataTemplate() {
return xxxxDataTemplate;
}
}
@Slf4j
@Data
public class xxxxImpl implements xxxxMessage {
private MQContext mqContext;
private JobInfo jobInfo;
private PythonExecutor pythonExecutor;
public xxxxImpl(MQContext mqContext, JobInfo jobInfo) {
this.jobInfo = jobInfo;
this.mqContext = mqContext;
init();
}
private void init() {
WorkWrapper workWrapper = new WorkWrapper(mqContext);
//这里为new出来的类对象
this.pythonExecutor = workWrapper.wrapper(new PythonExecutor(mqContext, jobInfo));
}
@Override
public void xxxxMsg(String message) {
//这里为使用new出来的类对象
Map<String, Object> result = pythonExecutor.execute(parseResult, message);
}
public class PythonExecutor {
private MQContext mqContext;
private JobInfo jobInfo;
@Autowired
public PythonExecutor(MQContext mqContext, JobInfo jobInfo) {
this.mqContext = mqContext;
this.jobInfo = jobInfo;
}
public Map<String, Object> execute(List<Map<String, Object>> parseResult, String message) {
//这里为获取方式
log.info("pythonUrl的值:{}",mqContext.getAdminMysqlDataTemplate().getUrlMap());
Map<String,String> urlMap = mqContext.getAdminMysqlDataTemplate().getUrlMap();
log.info("urlMap的值:{}",urlMap);
}
}
这样apollo里面的配置无论怎么改都能够获取到最新的
2024-07-18 03:09:16.300 [PYProcessingExecutor5] INFO - traceId:[AC13000168025674CD4D5838A0B43119] com.opay.gerudo.runner.comsumer.runing.impl.process.PythonExecutor -- pythonUrl的值:{JG20240524021458223=http://xxx.xxx.xxx:1280/job/py3/, JG20231214074930257=http://xxx.xxx.xxx:1280/job/indo/}
2024-07-18 03:09:16.300 [PYProcessingExecutor5] INFO - traceId:[AC13000168025674CD4D5838A0B43119] com.opay.gerudo.runner.comsumer.runing.impl.process.PythonExecutor -- urlMap的值:{JG20240524021458223=http://xxx.xxx.xxx:1280/job/py3/, JG20231214074930257=http://xxx.xxx.xxx:1280/job/indo/}