@ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效;
Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進來;@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.xsd">
-
-
- <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
- </beans>
@ImportResource(locations = {"classpath:beans.xml"})
導入Spring的配置文件讓其生效
- @SpringBootApplication
- @ImportResource(locations = {"classpath:beans.xml"})
- public class App {
-
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
測試
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class YamlApplicationTests {
-
- @Autowired
- ApplicationContext applicationContext;
-
- @Test
- public void contextLoads() {
- System.out.println(applicationContext.containsBean("HelloService"));
- }
-
- }
SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式
1、配置類@Configuration------>Spring配置文件
2、使用@Bean給容器中添加組件
- /**
- * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
- *
- * 在配置文件中用<bean><bean/>標籤添加組件
- *
- */
- @Configuration
- public class MyAppConfig {
-
- //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
- @Bean
- public HelloService helloService02(){
- System.out.println("配置類@Bean給容器中添加組件了...");
- return new HelloService();
- }
- }
啓動項目容器中就會有id爲helloService02的類了,@Configuration也是一個組件,你懂的噢
ok,簡單明瞭的結束本編博客,希望看明白的可以點個贊,或者轉發一下噢