Spring injects Beans into List/Map

Table of Contents

Spring injects Beans into List/Map

Inject into List

Inject into Map

Summarize


Spring injects Bean into List/Map

In the Spring framework, we often need to use collection types (such as List, Map, etc.) to store a set of Bean objects in applications. Through Spring’s dependency injection feature, we can easily inject multiple beans into a List or Map and use them in the application. This article will introduce how to use Spring to inject Beans into List and Map.

Inject into List

First, we need to define the Bean object we want to inject in the configuration file (such as applicationContext.xml). Suppose we have a UserService interface and two implementation classes UserServiceImpl1 and UserServiceImpl2:

xmlCopy code<bean id="userService1" class="com.example.UserServiceImp1" />
<bean id="userService2" class="com.example.UserServiceImp2" />

Next, we need to create a List and inject the above two Bean objects into the List. Add the following code in the configuration file:

xmlCopy code<util:list id="userServiceList">
    <ref bean="userService1" />
    <ref bean="userService2" />
</util:list>

In this way, we successfully injected userService1 and userService2 into the List named userServiceList. In Java code, we can use @Autowired or @Resource annotations to inject this List into the class we want to use:

javaCopy code@Autowired
private List<UserService> userServiceList;

Now, we can use userServiceList in our code.

Inject into Map

Similarly, we can also inject Beans into Map. Suppose we have a RoleService interface and two implementation classes RoleServiceImpl1 and RoleServiceImpl2:

xmlCopy code<bean id="roleService1" class="com.example.RoleServiceImp1" />
<bean id="roleService2" class="com.example.RoleServiceImp2" />

Now, we need to create a Map and inject the above two Bean objects into the Map. Add the following code in the configuration file:

xmlCopy code<util:map id="roleServiceMap">
    <entry key="role1" value-ref="roleService1" />
    <entry key="role2" value-ref="roleService2" />
</util:map>

In this way, we successfully injected roleService1 and roleService2 into the Map named roleServiceMap. In Java code, we can also use @Autowired or @Resource annotations to inject this Map into the class we want to use:

javaCopy code@Autowired
private Map<String, RoleService> roleServiceMap;

Now, we can use roleServiceMap in our code.

Summary

By injecting Beans into List and Map through Spring, we can easily manage and use a set of Bean objects. Just define the Bean object in the configuration file and inject it into the collection type, and then reference it in the code using dependency injection. This approach allows us to handle and configure multiple Bean objects more flexibly, improving the maintainability and scalability of the code. The above is a brief introduction and example of Spring injecting Beans into List/Map. I hope it can help you better use the Spring framework for development. thanks for reading!

In actual development, we often need to inject multiple Bean objects that implement the same interface into a List or Map. The following is a simple example to demonstrate how to use Spring to inject Beans into List and Map.

Suppose we are developing an e-commerce system and need to manage products in different categories. We define an interface??ProductService?? to manage products, and then have multiple implementation classes to handle different categories of products. First, we need to define the Bean object we want to inject in the configuration file (such as applicationContext.xml). Suppose we have the following implementation class:

javaCopy codepublic interface ProductService {
    void addProduct(Product product);
    List<Product> getAllProducts();
}
public class ClothingProductService implements ProductService {
    private List<Product> clothingProducts;
    public void addProduct(Product product) {
        // Add the specific implementation of clothing products
        clothingProducts.add(product);
    }
    public List<Product> getAllProducts() {
        // Get the specific implementation of all clothing products
        return clothingProducts;
    }
}
public class ElectronicsProductService implements ProductService {
    private List<Product> electronicsProducts;
    public void addProduct(Product product) {
        // Add the specific implementation of electronic products
        electronicsProducts.add(product);
    }
    public List<Product> getAllProducts() {
        // Get the specific implementation of all electronic products
        return electronicsProducts;
    }
}

Next, we need to inject the above two Bean objects into a List in the configuration file. Add the following code in the configuration file:

xmlCopy code<bean id="clothingProductService" class="com.example.ClothingProductService" />
<bean id="electronicsProductService" class="com.example.ElectronicsProductService" />
<util:list id="productServiceList">
    <ref bean="clothingProductService" />
    <ref bean="electronicsProductService" />
</util:list>

In this way, we successfully injected ??clothingProductService?? and ??electronicsProductService?? into the List named ??productServiceList?? middle. In Java code, we can use the ??@Autowired?? annotation to inject this List into the class we want to use:

javaCopy code@Autowired
private List<ProductService> productServiceList;

Now, we can use ??productServiceList?? in the code to operate products of different categories.

Similarly, we can also inject Beans into Map. Continuing in the e-commerce system, we can define a ??CategoryService?? interface to manage the classification of goods, and have multiple implementation classes to handle goods of different categories. First, we need to define the Bean object we want to inject in the configuration file. Suppose we have the following implementation class:

javaCopy codepublic interface CategoryService {
    void addProduct(Product product);
    List<Product> getAllProducts();
}
public class ClothingCategoryService implements CategoryService {
    private List<Product> clothingProducts;
    public void addProduct(Product product) {
        // Add the specific implementation of clothing products
        clothingProducts.add(product);
    }
    public List<Product> getAllProducts() {
        // Get the specific implementation of all clothing products
        return clothingProducts;
    }
}
public class ElectronicsCategoryService implements CategoryService {
    private List<Product> electronicsProducts;
    public void addProduct(Product product) {
        // Add the specific implementation of electronic products
        electronicsProducts.add(product);
    }
    public List<Product> getAllProducts() {
        // Get the specific implementation of all electronic products
        return electronicsProducts;
    }
}

Then, inject the above two Bean objects into a Map in the configuration file. Add the following code in the configuration file:

xmlCopy code<bean id="clothingCategoryService" class="com.example.ClothingCategoryService" />
<bean id="electronicsCategoryService" class="com.example.ElectronicsCategoryService" />
<util:map id="categoryServiceMap">
    <entry key="clothing" value-ref="clothingCategoryService" />
    <entry key="electronics" value-ref="electronicsCategoryService" />
</util:map>

In this way, we successfully injected ??clothingCategoryService?? and ??electronicsCategoryService?? into the Map named ??categoryServiceMap?? middle. In Java code, we can also use the ??@Autowired?? annotation to inject this Map into the class we want to use:

javaCopy code@Autowired
private Map<String, CategoryService> categoryServiceMap;

Now, we can use ??categoryServiceMap?? in the code to operate products in different categories.

In the Spring framework, “injection” refers to passing an instance of one object to another object to satisfy the dependencies between objects. Through Dependency Injection (DI), Spring can manage dependencies between objects and help developers more flexibly design and assemble various components of applications. In Spring, there are many ways to implement dependency injection, such as through constructors, setter methods, member variables, etc. Through injection, we can hand over the creation and maintenance of dependencies to the Spring container when writing code, making the components of the system more loosely coupled and easier to expand and maintain. The following is a detailed introduction to several commonly used Spring injection methods:

  1. Constructor injection: By accepting dependent objects as parameters in the object’s constructor, and then configuring instances of these dependent objects in the Spring container, the Spring container will automatically call the appropriate constructor to create the object when creating the object, and will depend on the object. incoming. For example:
javaCopy codepublic class UserService {
    private UserDao userDao;
    
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }
    
    // ...
}
xmlCopy code<bean id="userDao" class="com.example.UserDao" />
<bean id="userService" class="com.example.UserService">
    <constructor-arg ref="userDao" />
</bean>
  1. Setter method injection: Accept dependent objects by defining corresponding setter methods in the object, and then configure instances of these dependent objects in the Spring container. The Spring container will automatically call the setter method to set the dependent objects after creating the object. For example:
javaCopy codepublic class UserService {
    private UserDao userDao;
    
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    
    // ...
}
xmlCopy code<bean id="userDao" class="com.example.UserDao" />
<bean id="userService" class="com.example.UserService">
    <property name="userDao" ref="userDao" />
</bean>
  1. Annotation injection: Instruct the Spring container to inject by adding annotations on the object’s class, property or method. Spring provides a series of dependency injection-related annotations, such as @Autowired, @Resource, etc. For example:
javaCopy codepublic class UserService {
    @Autowired
    private UserDao userDao;
    
    // ...
}
xmlCopy code<bean id="userDao" class="com.example.UserDao" />
<context:annotation-config />
<bean id="userService" class="com.example.UserService" />

These are just a few common methods of Spring injection. In fact, the Spring framework also supports more injection methods, such as interface-based injection, automatic assembly, etc. By choosing an injection method that suits the project’s needs, you can make better use of the dependency injection features provided by the Spring framework and promote code reuse, flexibility, and testability.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java skill treesetList interface 139322 people are learning the system