Spring @Value 在 Spring Boot 2.5.5 中不起作用,获取空值

Sav*_*ola 0 properties-file spring-boot

我试图通过 Spring @Value 注释将一些属性值注入到变量中,但我得到空值。我尝试了不同的配置和技巧,但它不起作用。想想今天之前一切都运转正常。我不知道我改变了什么才能把事情搞砸。

这是我的java类:

@Component
@ConditionalOnProperty(prefix = "studioghibli", name = "get")
public class StudioGhibliRestService {

    @Value("${studioghibli.basepath}")
    private static String BASE_PATH;

    @Value("${studioghibli.path}")
    private static String PATH;

    @Value("${studioghibli.protocol:http}")
    private static String PROTOCOL;

    @Value("${studioghibli.host}")
    private static String HOST;

    private static String BASE_URI = PROTOCOL.concat("://").concat(HOST).concat(BASE_PATH).concat(PATH);

    @Autowired
    StudioGhibliRestConnector connector;

    public List<StudioGhibliFilmDTO> findAllFilms() throws SipadContenziosoInternalException {
        var response = connector.doGet(BASE_URI, null, null);
        if (!response.getStatusCode().is2xxSuccessful() || !response.hasBody()) {
            throw new SipadContenziosoInternalException(Errore.INTERNAL_REST_ERROR, "FindAll(), microservizio ".concat(BASE_URI), null);
        }
        return (List<StudioGhibliFilmDTO>) response.getBody();
    }

}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该类用 @Component 进行注释,因为我需要将其用作 @Service 层,以便在我的业务逻辑中进行休息调用。该类还以属性条件进行注释...

这是启动时调试窗口的屏幕截图:

调试窗口

由于协议值为空,因此我在启动时立即收到空指针异常。

这是 application-dev.properties 文件的一部分:

studioghibli.get
studioghibli.protocol=https
studioghibli.host=ghibliapi.herokuapp.com
studioghibli.basepath=/
studioghibli.path=/films

Run Code Online (Sandbox Code Playgroud)

And*_*tov 6

首先,@Value注释不适用于静态字段。

其次,@Value当 Spring 创建类的实例(bean)时,会处理带有注释的字段,但是类(对于任何实例)都存在静态字段,因此当编译器尝试定义静态字段时,BASE_URI其他字段不会尚未定义,因此您在启动时会得到 NPE。

因此,您可能需要重构,尝试使用构造函数注入值,如下所示:

@Component
@ConditionalOnProperty(prefix = "studioghibli", name = "get")
public class StudioGhibliRestService {
    
    private final StudioGhibliRestConnector connector;

    private final String baseUri;

    public StudioGhibliRestService(StudioGhibliRestConnector connector,
            @Value("${studioghibli.basepath}") String basePath,
            @Value("${studioghibli.path}") String path,
            @Value("${studioghibli.protocol:http}") String protocol,
            @Value("${studioghibli.host}") String host) {

        this.connector = connector;
        this.baseUri = protocol.concat("://").concat(host).concat(basePath).concat(path);
    }

    // other code

}
Run Code Online (Sandbox Code Playgroud)