How can you inject Java Collection in Spring?
How can you inject Java Collection in Spring?
In Spring, you can inject Java Collections such as List
, Set
, Map
, and Properties
into beans using various methods of dependency injection provided by the framework. Here are the primary ways to achieve this:
Constructor injection is a method where the dependencies are provided through a class constructor. You can annotate the constructor with @Autowired
to indicate that Spring should inject the dependencies when creating an instance of the class. The constructor parameters should be of the collection types you want to inject, such as List<String>
, Set<Long>
, or Map<Long, String>
.
For example:
@Component
public class ConstructorInjection {
private List<String> names;
private Set<Long> phones;
private Map<Long, String> phoneNameMap;
@Autowired
public ConstructorInjection(List<String> names, Set<Long> phones, Map<Long, String> phoneNameMap) {
this.names = names;
this.phones = phones;
this.phoneNameMap = phoneNameMap;
}
// Getters and setters omitted for brevity
}
The respective collection types are configured in a Java configuration class annotated with @Configuration
, and the collection beans are defined using the @Bean
annotation[2].
Setter injection involves using setter methods to set the dependencies. You can define setter methods in your class and annotate them with @Autowired
. Spring will then use these methods to inject the collection dependencies.
For example:
public class SetterInjection {
private List<String> names;
@Autowired
public void setNames(List<String> names) {
this.names = names;
}
}
Field injection is done by placing @Autowired
annotations directly on the fields. However, it is not recommended to use field-based injection as it can have a performance impact. Instead, constructor or setter-based injections are preferred.
For example:
@Component
public class FieldInjection {
@Autowired
private List<String> names;
// Other fields and methods omitted for brevity
}
You can also define collections in XML configuration files using the <list>
, <set>
, <map>
, and <props>
elements. This approach is less common with the advent of annotation-based configuration but is still supported.
For example:
<bean id="javaCollection" class="com.exa...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào