[英]Spring Boot Failed to use @Value for injection
Spring 引導版本<version>2.2.0.RELEASE</version>
描述:
com.shawn.foodrating.service.impl.AdServiceImpl
java.lang.Integer
的 bean。
行動:
考慮在你的配置中定義一個“java.lang.Integer”類型的bean。
@Service
@Transactional(rollbackOn = Exception.class)
@AllArgsConstructor
public class AdServiceImpl implements AdService {
private AdRepository repository;
private FileService fileService;
@Value("${app.ad.DefaultPageSize}")
private Integer DEFAULT_PageSize;
@Value("${app.ad.ImagePath}")
private String AD_IMAGE_PATH;
@Value("${app.ad.ImageUrl}")
private String AD_IMAGE_URL;
加載屬性文件
@SpringBootApplication
@PropertySource("classpath:app.properties")
public class FoodRatingApplication {
public static void main(String[] args) {
SpringApplication.run(FoodRatingApplication.class, args);
}
}
不確定它有什么問題。
當您使用 Lombok 的@AllArgsConstructor
時,它必須為您的所有字段創建一個構造函數,那些帶有@Value
注釋的字段和那些沒有注釋的字段。
現在 Lombok 甚至對 spring 的@Value
注釋一無所知。 所以生成的構造函數看起來像這樣:
public AdServiceImpl(AdRepository repository, FileService fileService, Integer DEFAULT_PageSize, String AD_IMAGE_PATH, String AD_IMAGE_URL) {
this.repository = repository;
....
}
您可以運行 Delombok 來查看實際生成的代碼。
另一方面,Spring 在這種情況下看到單個構造函數嘗試調用它來創建 bean ( AdServiceImpl
),並且只有在此之后迭代其字段並注入由@Value
注釋的數據。
Now, when spring calls the constructor, it sees an integer (DEFAULT_PageSize), has no clue that its a value (and spring has to inject something brcause its a constructor injection), and throws an Exception.
所以在分辨率方面:
在這種情況下不要使用 lombok 的所有 args 構造函數,而是只為AdRepository
和FileService
創建一個非 lombok 構造函數)
或者使用 @Value 注釋參數創建構造函數,而不是字段注入(刪除字段上的 @Value):
public AdServiceImpl(AdRepository repository, FileService fileService, @Value(${app.ad.DefaultPageSize}"} Integer DEFAULT_PageSize, @Value(...) String AD_IMAGE_PATH, @Value(...) String AD_IMAGE_URL) {
this.repository = repository;
....
}
使用以下行添加到 projeck lombok.config 文件:
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
根本原因是您使用 Lombok @AllArgsConstructor而某些屬性由@Value(..)填充。
將 @AllArgsConstructor 替換為@RequiredArgsConstructor並試一試。
注意:添加此評論以供將來參考。
您可以按以下方式使用。
@Service
@Configuration
@ComponentScan
@PropertySource("classpath:app.properties")
@Transactional(rollbackOn = Exception.class)
@AllArgsConstructor
public class AdServiceImpl implements AdService {
private AdRepository repository;
private FileService fileService;
@Value("${app.ad.DefaultPageSize}")
private Integer DEFAULT_PageSize;
@Value("${app.ad.ImagePath}")
private String AD_IMAGE_PATH;
@Value("${app.ad.ImageUrl}")
private String AD_IMAGE_URL;
要使用@Value
注解,您必須在同一個 class 中使用@Configuration
和@PropertySource
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.