Câu hỏi phỏng vấn Spring
Câu hỏi

How can you inject Java Collection in Spring?

Câu trả lời

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

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

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

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
}

XML Configuration

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

middle

Gợi ý câu hỏi phỏng vấn

middle

What is Spring IoC Container?

junior

How to integrate Java Server Faces (JSF) with Spring?

senior

What are the different types of Advices?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào