[英]Spring @Value not working in Spring Boot 2.5.5, getting null values
我試圖通過 Spring @Value 注釋將一些屬性值注入變量,但我得到 null 值。 我嘗試了不同的配置和 triks 但它不起作用。 認為在今天之前,everythink 工作正常。 我不知道我為了弄壞東西而改變了什么。
這是我的 java class:
@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();
}
}
如您所見,class 用@Component 注釋,因為我需要將它用作@Service 層,以便在我的業務邏輯中調用 rest。 class 也以屬性為條件進行注釋......
這是啟動時調試 window 的屏幕截圖:
由於 PROTOCOL 值為 null,我在啟動時立即得到 null 指針異常。
這是 application-dev.properties 文件的一部分:
studioghibli.get
studioghibli.protocol=https
studioghibli.host=ghibliapi.herokuapp.com
studioghibli.basepath=/
studioghibli.path=/films
首先,@Value 注釋不適用於@Value
字段。
Secondly, fields with @Value
annotation is processed when the instance of the class (a bean) is created by Spring, but static fields exist for a class (for any instance), so when the compiler is trying to define your static BASE_URI
field other字段尚未定義,因此您會在啟動時獲得 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
}
謝謝,它對我有用,我必須向我的項目添加一些代碼。 然后我檢查了“@Value”部分中的 spring 核心文檔。 除了
使用 JavaConfig 配置 PropertySourcesPlaceholderConfigurer 時,@Bean 方法必須是 static。
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.