Spring Boot @ImportResource 导入 Spring 配置文件
Jihongchang(讨论 | 贡献)2023年2月13日 (一) 05:32的版本
https://www.bilibili.com/video/BV19K4y1L7MT/?p=11
以前会使用 XML 配置文件进行 bean 装配,为了兼容旧的 通过 XML 配置文件进行 bean 装配的方式 使用 @ImportResource
<?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-3.0.xsd">
<bean id="haha" class="io.github.jihch.boot.bean.User">
<property name="name" value="zhangsan"/>
<property name="age" value="18"/>
</bean>
<bean id="hehe" class="io.github.jihch.boot.bean.Pet">
<property name="name" value="tomcat"/>
</bean>
</beans>
……
@ImportResource("classpath:beans.xml")
public class MyConfig {
……
@SpringBootApplication(scanBasePackages = "io.github.jihch")
public class MainApplication {
public static void main(String[] args) {
//1、返回 IOC 容器
ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] beanDefinitionNames = context.getBeanDefinitionNames();
Arrays.sort(beanDefinitionNames);
for (String name : beanDefinitionNames) {
System.out.println(name);
}
boolean tom = context.containsBean("tom");
System.out.println("容器中 tom 组件:" + tom);
boolean user01 = context.containsBean("user01");
System.out.println("容器中 user01 组件:" + user01);
boolean tom22 = context.containsBean("tom22");
System.out.println("容器中 tom22 组件:" + tom22);
boolean haha = context.containsBean("haha");
boolean hehe = context.containsBean("hehe");
System.out.println("haha:" + haha);
System.out.println("hehe:" + hehe);
}
}
容器中 tom 组件:false
容器中 user01 组件:true
容器中 tom22 组件:true
haha:true
hehe:true