使用@ImportResource 导入Spring配置文件的方式
首先我们在resources目下创建一个spring配置文件 bean.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="helloService" class="com.lbee.service.HelloService"></bean>
</beans>
接下来创建我们的 HelloService.java
package com.lbee.service;
/**
* @ClassName HelloService
* @Description TODO
* @Autchor lbee
* @Date 2019/3/4 22:30
* @Version 1.0
*/
public class HelloService {
public HelloService(){
System.out.println("hello 被加载了!");
}
}
然后在主程序类中添加@ImportResource注解
package com.lbee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource(value = {"classpath:beans.xml"})
public class HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
}
编写我们的单元测试,来判断一下helloService是否被spring所加载
package com.lbee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
boolean bool = ioc.containsBean("helloService");
System.out.println(bool);
}
}
执行结果
SpringBoot 推荐给容器添加组件的方式-@Bean
上面我们写了用@ImportResource注解导入spring配置文件的方式,但SpringBoot推荐我们使用更简便的全注解方式添加spring组件
首先我们创建一个配置文件类 MyAppConfig.java,也可以写在我们的主程序文件中
package com.lbee.config;
import com.lbee.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName MyAppConfig
* @Description TODO
* @Autchor lbee
* @Date 2019/3/4 22:53
* @Version 1.0
*/
@Configuration
public class MyAppConfig {
// 将方法的返回值添加到容器中,容器中这个组件的id默认为方法名
@Bean
public HelloService helloService() {
return new HelloService();
}
}
@Configuration:指明这是一个配置文件类
delete掉我们刚才在主程序类的 代码
@ImportResource(value = {"classpath:beans.xml"})
我们再次跑一下单元测试,输出结果
OK! helloService 依然被spring加载了