SoFunction
Updated on 2025-04-11

Springboot controls the method of inverting and bean objects

1 Control reversal

1.1 What is control reversal

Inversion of control (IoC) is a design principle that transfers responsibilities such as object creation, dependency injection, and lifecycle management from application code to frameworks or containers.

1.2 Control reversal in SpringBoot

Spring framework manages the life cycle and dependencies of beans through IoC containers, thereby achieving control inversion

2 Ioc container management of beans

2.1 What is a Bean object?

In the Spring framework, a Bean is an object managed by a Spring IoC container. The creation, initialization, dependency injection and destruction of beans are all handled by Spring containers. A bean can be any Java object, usually a POJO (Plain Old Java Object).

2.2 Bean registration process

2.2.1 Scan the Bean

  • In Spring applications, manually configuring each bean can be very tedious, especially in large projects. @ComponentScan simplifies this process by automatically scanning and registering beans, allowing developers to focus on business logic.
  • In Spring Boot applications, @ComponentScan is usually used with @SpringBootApplication annotation. The @SpringBootApplication annotation contains @ComponentScan, which will scan the package where the main class is located and its subpackages by default.
  • In the following example, Spring scans and all components under the package and its subpackages.
@Configuration   
@ComponentScan(basePackages = {"", ""})   
public class AppConfig {
}

2.2.2 Defining Beans

Using @Component and its derived annotations: Spring supports automatic scanning and registration of beans via @ComponentScan. Commonly used annotations include:

    @Component:General Annotations,Used to mark any class as Bean。
    @Service:Classes used to tag service layer。
    @Repository:Classes used to tag data access layer。
    @Controller:Classes for marking controller layers。
    @Configuration:Used to mark configuration classes。

Use @Bean annotation: In the configuration class, you can use @Bean annotation to explicitly define the bean. @Bean is usually used to define classes in third-party libraries or beans that require custom configuration.

@Configuration// Configuration annotationpublic class CommonConfig {
    /**
      * @Bean annotation method will be called by the Spring container and the return value will be registered as a Bean
      */
    @Bean
    public Country country(){
        return new Country();
    }
     /**
      * By default, the name of the bean is the method name.  You can specify the name of the Bean through the name or value attributes.
      */
    @Bean(name = "customService")
    public MyService myService() {
        //The name of Bean is customService, not the default myService.        return new MyService();
    }
}

3. Registration based on XML configuration: In earlier Spring versions, beans were usually registered through XML configuration files. Although annotations are recommended now, XML configuration still supports

<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans
           /schema/beans/">
    <!-- Register one Bean -->
    <bean  class=""/>
</beans>

Conditional Bean Registration: Conditional Bean Registration can be achieved by combining conditional annotations (such as @ConditionalOnProperty, @ConditionalOnClass, etc.).

@Configuration
public class CommonConfig {
    /**
      * Use @ConditionalOnProperty conditional injection: the prefix in the configuration file is province, and the value of the property name is wfs, then declare this bean
      * @ConditionalOnMissingBean declares the bean of the current type when there is no bean of the current type
      * @ConditionalOnClass The bean is declared when the specified class exists under the classpath
      */
    @ConditionalOnProperty(prefix = "province",name = "name" ,havingValue = "wfs")
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = "")
    public Province province(@Value("${}") String name,
                             @Value("${}") String direction) {
        Province province = new Province();
        (name);
        (direction);
        return province;
    }
}

2.3 @import annotation

The @Import annotation is used to introduce other configuration classes or components into the current configuration class. It provides a modular way to organize the configuration of Spring applications, avoiding concentrating all configurations in one class. Preferential use of @ComponentScan: If you can scan the class through @ComponentScan, try to use @ComponentScan instead of @Import. As in the following example:

Startup class

/*
 1@Import can be annotated on the @Configuration class or @Component class, and is used to import other configuration classes or component classes.
 2@Import can import multiple configuration classes at the same time.
 3@Import can also import classes that implement the ImportSelector interface, which are used to dynamically select the configuration class or component class to be imported.
 */
@Import()//Use @Import to import ImportSelector//@Import()
@SpringBootApplication
public class SpringbootBeanRegisterApplication {
    public static void main(String[] args) {
      ApplicationContext context =  (, args);//Get the ioc container      Country country = ();//Get bean      (country);
      (("aa"));

/**
  * @ImportSelector: Import selector
  * Function: Import the specified configuration class
  */
public class CommonImportSeletor implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{""};
    }
}

2.4 Bean registration order

  • Configuration class: Prioritize the @Configuration class.
  • Component class: Scan and register a class with @Component and its derived annotations.
  • Manually registered beans: handle beans defined by @Bean annotation.

2.5 Dependency injection of beans

Constructor injection: Recommended method, suitable for mandatory dependencies.

@Service
public class MyService {
    private final MyRepository repository;
    @Autowired
    public MyService(MyRepository repository) {
         = repository;
    }
}

Setter Injection: Suitable for optional dependencies

@Service
public class MyService {
    private MyRepository repository;
    @Autowired
    public void setRepository(MyRepository repository) {
         = repository;
    }
}

Field injection: Not recommended because it is not conducive to testing and code readability.

@Service
public class MyService {
    @Autowired
    private MyRepository repository;
}

This is the article about Springboot control inversion and Bean objects. For more related Springboot control inversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!