该注解主要用于导入其他 Spring 配置文件
- 我们在项目的 resource 包下新建一个 beans.xml 配置文件,然后注册一个 Bean
<?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">
<bean name="pet" class="com.study.springboot.entity.Pet"/>
</beans>
- 在项目的配置类上添加 @ImportResource 注解,引入 beans.xml 配置文件
@Configuration
@ImportResource("classpath:beans.xml")
public class AppConfig {}
- 在启动类中测试一下
@SpringBootApplication
public class SpringbootStudyApplication {
public static void main(String[] args) {
// 1.返回 IOC 容器
ConfigurableApplicationContext context = SpringApplication.run(SpringbootStudyApplication.class, args);
// 2.查看容器中是否有名为 pet 的 Bean
System.out.println(context.containsBean("pet")); // true
}
}