Spring自动关联列表
是否可以将Spring自动关联列表,spring,list,autowired,Spring,List,Autowired,是否可以将@Autowired与列表一起使用 比如我有一个带有mimetypes的属性文件,在我的类文件中,我有这样的东西 @Autowired private List<String> mimeTypes = new ArrayList<String>(); @Autowired 私有列表mimeTypes=new ArrayList(); 只要列表是一个bean,您就应该能够自动连接它。然后使用@限定符告诉Spring要使用哪个bean/列表。请参见我认为您至少需要
@Autowired
与列表一起使用
比如我有一个带有mimetypes的属性文件,在我的类文件中,我有这样的东西
@Autowired
private List<String> mimeTypes = new ArrayList<String>();
@Autowired
私有列表mimeTypes=new ArrayList();
只要列表是一个bean,您就应该能够自动连接它。然后使用@限定符告诉Spring要使用哪个bean/列表。请参见我认为您至少需要一个限定符。对“新”的呼吁似乎与使用Spring的想法相反。你混淆了Spring的角色。如果调用“new”,则对象不受Spring的控制。您甚至可以在Spring.xml中创建一个java.util.List
,并通过@限定符将其注入应用程序。从springsource:
pechorin@hero.org
raskolnikov@slums.org
stavrogin@gov.org
porfiry@gov.org
因此,这会将您的接线更改为:
@Autowired
@Qualifier("emails")
private List<String> mimeTypes = new ArrayList<String>();
@Autowired
@限定词(“电子邮件”)
私有列表mimeTypes=new ArrayList();
我建议使用这种方法,因为您正在注入字符串列表
干杯
编辑
如果要插入属性,请查看此@Qualifier(“…”)
不受鼓励,请尝试使用
private@Resource(name=“…”)列出模拟类型;
另请参见。Spring 4及更早版本支持自动收集给定类型的所有bean并将其注入集合或数组的功能
以下是一个例子:
@Component
public class Car implements Vehicle {
}
@Component
public class Bus implements Vehicle {
}
@Component
public class User {
@Autowired
List<Vehicle> vehicles; // contains both car and bus
}
@组件
公车{
}
@组成部分
公车{
}
@组成部分
公共类用户{
@自动连线
列出车辆;//包含汽车和公共汽车
}
Ref:如果自动连线bean在同一(@Configuration
)类中声明,并且您需要它来声明另一个bean,那么下面的工作方式是:
@Bean
public BeanWithMimeTypes beanWithMimeTypes() {
return new BeanWithMimeTypes(mimeTypes());
}
@Bean
public List<String> mimeTypes() {
return Arrays.<String>asList("text/html", "application/json);
}
@Bean
公共BeanWithMimeTypes BeanWithMimeTypes(){
返回具有mimeTypes(mimeTypes())的新Bean;
}
@豆子
公共列表mimeTypes(){
返回Arrays.asList(“text/html”、“application/json”);
}
当然,即使您在另一个配置中重写了mimeTypes
bean,它也会正常运行。不需要显式的@Qualifier
或@Resource
注释。它只会覆盖整个对象。Spring不知道(或不在乎)使用原型范围的bean,你甚至可以使用新的
,并且仍然有bean spring管理。顺便说一句,已经有一段时间了-如果任何答案是有用的,请将其标记为正确的,以便其他具有相同问题的人可以轻松识别任何有用的答案。可能是+1的重复我只是想弄明白为什么我不能让这个场景工作。当没有定义这种类型的bean时会发生什么?它会自动连接一个空的吗list@user2798694它应该为空或null。这只是演示如何使用构造函数(这是可以的)。但需要指出的是,在本例中,不需要使用@Bean注释mimeTypes(),除非您希望其结果在应用程序上下文中可用,而不是创建BeanWithMimeTypes组件。难道该类型的所有Bean都不会自动连接到列表中吗?
@Component
public class Car implements Vehicle {
}
@Component
public class Bus implements Vehicle {
}
@Component
public class User {
@Autowired
List<Vehicle> vehicles; // contains both car and bus
}
@Bean
public BeanWithMimeTypes beanWithMimeTypes() {
return new BeanWithMimeTypes(mimeTypes());
}
@Bean
public List<String> mimeTypes() {
return Arrays.<String>asList("text/html", "application/json);
}