![](/img/trans.png)
[英]Java Spring: How to use `@Value` annotation to inject an `Environment` property?
[英]How to use @Inject annotation properly in spring Java based configuration?
我是春季新手,在某些方面遇到了困難,如下所述-
我有一個類顏色,具有兩個不同的實現名稱,分別是Red和Blue,我想使用@inject
將它們都注入到顏色列表中。
Below is my ApplicationConfiguration class
package org.arpit.java2blog.config;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Inject;
import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(CountryConfig.class)
public class ApplicationConfiguration {
@Inject
private List<Color> colorList;
@Bean
public List<Color> colorList() {
System.out.println("Second");
List<Color> aList = new ArrayList<Color>();
aList.add(new Blue());
return aList;
}
}
但是作為例外
自動連接的依賴項注入失敗; 嵌套的異常是org.springframework.beans.factory.BeanCreationException:無法自動連線字段:私有java.util.List org.arpit.java2blog.config.ApplicationConfiguration.colorList; 嵌套的異常是org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到依賴項[org.arpit.java2blog.config.Color]的類型為[org.arpit.java2blog.config.Color]的合格Bean:預期至少為1有資格作為此依賴項自動裝配候選者的bean。 依賴注釋:{@ javax.inject.Inject()}
下面的代碼帶有內聯注釋,顯示了使用@Inject
填充colorList
的正確方法:
@Configuration
@Import(CountryConfig.class)
public class ApplicationConfiguration {
@Inject
private List<Color> colorList;
@Bean
public Color color() {
return new Blue();//injects Blue object to colorList
}
@Bean
public Color color() {
return new Red();//injects Red object to colorList
}
}
另外,您可以很好地使用@Order
在內部的colorList
的特定索引處注入Color
對象,如Spring doc 此處所述 。
如果我從紅色和藍色類中都刪除了@component批注,並且在刪除組件后僅提供一種bean類型,則該解決方案工作正常
當您使用@Component
標記bean類時(對於任何Spring colorList
型注釋都有效),這些bean將可以注入並且將自動加載到colorList
。 因此,當您提供@Bean
批注方法並再提供一個對象時,該對象也將添加到列表中,但是通常,您將使用@Component
或@Bean
來加載列表,但不能同時使用兩者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.