@ImportResource of springboot: Import Spring configuration file~

@ImportResourceThe function is to allow other configuration files to be imported into the Spring configuration file . By using the @ImportResource annotation, Bean definitions defined in other configuration files can be imported into the current configuration file, thereby achieving modularization and reuse of the configuration file. This makes it easy to combine different configuration files and improve the readability and management of configuration files.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="MyUser1" class="com.springboot.User">
        <property name="name" value="张三"></property>
        <property name="age" value="18"></property>
    </bean>
    <bean id="MyPet1" class="com.springboot.Pet">
        <property name="name" value="小猫"></property>
    </bean>
</beans>

As shown below, when we were learning spring before, we configured beans through XML files. The beans configured in this way cannot be obtained through springboot. The test is as follows:

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class MainApplication {
    
    
    public static void main(String[] args) {
    
    
      ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args);
      Boolean user1= (Boolean) run.containsBean("MyUser1");
      System.out.println(user1);//输出false
      Boolean pet1= (Boolean) run.containsBean("MyPet1");
      System.out.println(pet1);//输出false
    }
}

In order to improve the readability and management of files, we can combine the two as follows:

We only need to add the following annotation to any custom configuration class, and the annotation indicates the name of the XML file!

@ImportResource("classpath:beans.xml")

After retesting, the output is all true.

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133555566
Recommended