一、导入XML配置文件到容器中(@ImportResource)
(一)第一步:在resources目录下新建一个XML文件,并加入相关内容
加入一下代码:
<?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
id="springboot06service"
class="com.aliq.springboot02helloworld.service.SpringBoot06Note"/>
</beans>
注意这里的id!
(二)第二步:在主程序中加入@ImportResource
注解
@ImportResource(locations = "classpath:springboot06note.xml")//倒入Spring配置文件
@SpringBootApplication
public class SpringBoot02HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot02HelloworldApplication.class, args);
}
}
说明: @ImportResource指向了XML文件的类路径
(三)运行测试
@SpringBootTest
class SpringBoot02HelloworldApplicationTests {
//获取ioc容器对象
@Autowired
ApplicationContext ioc;
//Note06测试1:导入 xml 配置文件
@Test
void testIOC01(){
Boolean b =ioc.containsBean("springboot06service");//返回true则成功,返回false则失败。
System.out.println("_____________________"+b+"_____________________");
}
}
非常关注: 此处的containBean的参数就是XML文件中Bean标签的id!
测试结果:
二、导入Java配置文件
(一)写一个JavaBean文件来作为我们测试的返回值(空的也行)
package com.aliq.springboot02helloworld.service;
public class SpringBoot06Note {
}
(二)写一个配置类并加上相关注解
package com.aliq.springboot02helloworld.config;
import com.aliq.springboot02helloworld.service.SpringBoot06Note;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //这个注解告诉SpringBoot这是一个配置类
public class MyAppConfig {
@Bean //这个注解把方法的返回值加到容器中,Bead的id默认是方法明名。
public SpringBoot06Note getConfig(){
System.out.println("_____________________已执行_____________________");
return new SpringBoot06Note();
}
}
(三)测试运行
import com.aliq.springboot02helloworld.bean.Note;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class SpringBoot02HelloworldApplicationTests {
//获取ioc容器对象
@Autowired
ApplicationContext ioc;
//Note06测试2:导入Java 配置文件
@Test
void testIOC02(){
Boolean b =ioc.containsBean("getConfig");
System.out.println("_____________________"+b+"_____________________");
}
}
运行结果:
OK! 结果出来了!