java - 为什么 PostConstruct 方法在 springboot 中使用时不能保持 b

我在数据库里有一些配置信息,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仍然得到 0RedisClusterDaoImpl类。

最佳答案

使用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 剪贴板读取不适用于

python - 我的碰撞函数中的 For 循环从未命中?

ios - 快速用户界面 | onDrag - 自定义(dragItem)预览图像外观

node.js - 无法在谷歌云功能中调试 Puppeteer 超时

apache-spark - 如何在 pyspark 数据帧读取方法中包含分区列

reactjs - Expo React-Native 调试器 - 错误 : Unable to r

python - django循环静态文件目录

python - 如何在python中调整直方图上的字体大小

node.js - 如何仅将受影响的 nx 服务部署到 GCP APP Engine