在控制器初始化问题期间使用@Value Spring 注释

use of @Value Spring annotation during Controller initialization issue

可能其他人也问过类似的问题,但我找不到提供有效解决方案的答案... 我正在学习 spring 引导,在我的实验中使用 guava RateLimiter 时,我遇到了以下问题: RateLimiter 需要在 Controller 初始化期间创建,但如果我想加载速率,我必须对其进行硬编码,因为如果我尝试使用带有 @Value Spring 注释的属性从 props 加载它,它不起作用。 这个“限制”有什么“技巧”吗? 请参阅下面的代码:

@RestController
public class LoggingController {
    private Logger logger = LoggerFactory.getLogger(LoggingController.class);

    @Value("${count}")
    private Double PERMITS_COUNT;
    @Value("${seconds}")
    private Double PERMITS_PER_SECONDS;
    @Value("${consumed}")
    private int PERMITS_CONSUMED;

//@ Value fails here with NullPointerException
    private RateLimiter rateLimiter = RateLimiter.create(PERMITS_COUNT / PERMITS_PER_SECONDS);
// This works file
private RateLimiter rateLimiter = RateLimiter.create(10d / 60d);

    private AtomicInteger index = new AtomicInteger(0);


    @GetMapping("/logging")
    @ResponseBody
    public String logging (@RequestParam(name="name", required=false, defaultValue="JavaBoss") String name) {

//@Value works fine if used here
        rateLimiter.setRate(PERMITS_COUNT / PERMITS_PER_SECONDS);
        rateLimiter.acquire(PERMITS_CONSUMED);
...

非常感谢...

使用 PostConstruct 应该没问题

 @RestController
    public class LoggingController {
        private Logger logger = LoggerFactory.getLogger(LoggingController.class);
    
        @Value("${count}")
        private Double PERMITS_COUNT;
        @Value("${seconds}")
        private Double PERMITS_PER_SECONDS;
        @Value("${consumed}")
        private int PERMITS_CONSUMED;
        
        private RateLimiter rateLimiter;
        
        @PostConstruct 
        private void createRateLimiter() {
         rateLimiter = RateLimiter.create(PERMITS_COUNT / PERMITS_PER_SECONDS);
        }
        
    
        private AtomicInteger index = new AtomicInteger(0);
    
    
        @GetMapping("/logging")
        @ResponseBody
        public String logging (@RequestParam(name="name", required=false, defaultValue="JavaBoss") String name) {
    
    
    ...