@Value 注解实例化为 null

问题描述 投票:0回答:1

我有一个非常简单的 SpringBoot 应用程序,我在其中定义了一个测试组件

package com.example.SpringBootDB_H2.model;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
    public class TestCompnent {
        @Value("${collateral.username}")
        private String username;
    
        public TestCompnent(){
          log.info("Username : {}",username);
        }
    
        public  TestCompnent(String username){
            this.username = username;
        }
    
    }

在“application.yml”中我有:

collateral:
           username: ABCD

但在启动时它会打印:

.e.SpringBootDB_H2.model.TestCompnent   : Username : null

为什么?

spring-boot annotations
1个回答
0
投票

我认为是关于Spring Bean的生命周期问题。 属性值是在调用构造函数后注入的,因此,通常,username 为 null。所以,如果你想检查你设置的属性是否合适,你可以在@PostConstruct处检查,而不是在构造函数中检查。

package com.example.SpringBootDB_H2.model;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class TestCompnent {
    @Value("${collateral.username}")
    private String username;

    public TestCompnent() {
        // Constructor is empty, injection hasn't happened yet
    }

    public TestCompnent(String username) {
        this.username = username;
    }

    // here
    @PostConstruct
    private void init() {
        log.info("Username : {}", username);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.