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.
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.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.