Spring 导入 XML 配置文件:@ImportResource

@ImportResource 是位于 org.springframework.context.annotation 包中的一个注解。@ImportResource 用于导入 XML 配置文件,作用是让 Spring 容器加载指定的 XML 配置文件,并将其中定义的 Bean 注册到 Spring 容器中,以便在应用程序中使用。

使用 @ImportResource 注解可以将一个或多个 XML 配置文件导入到 Spring 应用程序上下文中。这些 XML 配置文件中可以包含 Spring Bean 的定义、AOP 切面、数据源配置等内容。

@ImportResource 注解通常与 @Configuration 注解一起使用,以便在 Java Config 方式中导入 XML 配置文件。例如:

@Configuration
@ImportResource("classpath:app-beans.xml")
public class AppConfig {}

在同一个 @ImportResource 注解中支持配置多个 XML 配置文件的导入。例如:

@Configuration
@ImportResource({"classpath:aop-beans.xml", "classpath:app-beans.xml"})
public class AppConfig {}

对于上述案例中的 @ImportResource("classpath:app-beans.xml"),在 SpringBoot 声明周期中的体现是当 AppConfig 类被加载时,Spring 容器会自动加载 app-beans.xml 配置文件,并将其中定义的 Bean 注册到 Spring 容器中。假设在 app-beans.xml 配置文件的内容为:


<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">
    
    <bean id="app1" class="com.config.App1">
        <property name="appKey" value="123" />
        <property name="appSecret" value="456" />
    bean>

beans>

那么,在 AppConfig 类被加载时,将向 Spring IOC 容器中注入如下 app-beans.xml 配置文件中定义的 Bean:

<bean id="app1" class="com.config.App1">
    <property name="appKey" value="123" />
    <property name="appSecret" value="456" />
bean>

最终,ID 为 app1 的 Bean 将被加载到 Spring IOC 容器中。

你可能感兴趣的:(Spring,spring,xml,java,springboot,spring,boot,后端)