我在数据库里有一些配置信息,springboot启动的时候只会加载一次这些信息。所以我这样写代码:
@Configuration
public class CommonConfig {
private final DbConfigDao dbConfigDao;
@Autowired
public CommonConfig (DbConfigDao dbConfigDao) {
this.dbConfigDao = dbConfigDao;
}
private int redisStoreDays; //omit get,set method
@PostConstruct
public void init() {
redisStoreDays = dbConfigDao.getValueByKey("redisStoreDays");
//... continue to load the other config from db
}
}
在另一个 bean 中,我尝试获取 redisStoreDays
值,它返回 0
,但实际值为 1
.
@Configuration
public class AutoConfiguration {
@Conditional(RedisClusterConditional.class)
@Bean(name = "redisDao", initMethod = "init")
public RedisClusterDao getRedisClusterDao() {
return new RedisClusterDaoImpl();
}
@Conditional(RedisSentryConditional.class)
@Bean(name = "redisDao", initMethod = "init")
public RedisSentryConditional getRedisSentryDao() {
return new RedisSentryDaoImpl();
}
}
public class RedisClusterDaoImpl implements RedisDao {
@Autowired
private CommonConfig commonConfig;
private int storeDays = 7;
@Override
public void init() {
storeDays = 60 * 60 * 24 * commonConfig.getRedisStoreDays();
//commonConfig.getRedisStoreDays is 0 but in fact is 1
}
}
如何保持 bean 初始化顺序? 我尝试在我的 redis bean 中添加 PostConstruct,但它仍然不起作用。
我调试并找到 commonConfig
不为空,而是 commonConfig.getRedisStoreDays()
返回 0
.
执行后init
RedisClusterDaoImpl
中的方法, commonConfig.getRedisStoreDays()
变为 1。
我也尝试添加@AutoConfigureBefore(RedisClusterDao.class),但是storeDays
仍然得到 0
在 RedisClusterDaoImpl
类。
最佳答案
使用Spring的@DependsOn
,即:
@DependsOn("CommonConfig")
@Configuration
public class AutoConfiguration {
...
}
关于java - 为什么 PostConstruct 方法在 springboot 中使用时不能保持 bean init 顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63527766/
相关文章:
amazon-web-services - 登录后使用 cognito 返回 401 的亚马逊负载均
node.js - puppeteer overridePermissions 剪贴板读取不适用于
ios - 快速用户界面 | onDrag - 自定义(dragItem)预览图像外观
node.js - 无法在谷歌云功能中调试 Puppeteer 超时
apache-spark - 如何在 pyspark 数据帧读取方法中包含分区列
reactjs - Expo React-Native 调试器 - 错误 : Unable to r