@ImportResource和@Bean註解詳解,超詳細

 

@ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效;

Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;

想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
  6. </beans>

@ImportResource(locations = {"classpath:beans.xml"})
導入Spring的配置文件讓其生效

  1. @SpringBootApplication
  2. @ImportResource(locations = {"classpath:beans.xml"})
  3. public class App {
  4. public static void main(String[] args) {
  5. SpringApplication.run(App.class, args);
  6. }
  7. }

測試

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class YamlApplicationTests {
  4. @Autowired
  5. ApplicationContext applicationContext;
  6. @Test
  7. public void contextLoads() {
  8. System.out.println(applicationContext.containsBean("HelloService"));
  9. }
  10. }

SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式

1、配置類@Configuration------>Spring配置文件

2、使用@Bean給容器中添加組件

  1. /**
  2. * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
  3. *
  4. * 在配置文件中用<bean><bean/>標籤添加組件
  5. *
  6. */
  7. @Configuration
  8. public class MyAppConfig {
  9. //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
  10. @Bean
  11. public HelloService helloService02(){
  12. System.out.println("配置類@Bean給容器中添加組件了...");
  13. return new HelloService();
  14. }
  15. }

啓動項目容器中就會有id爲helloService02的類了,@Configuration也是一個組件,你懂的噢

 

ok,簡單明瞭的結束本編博客,希望看明白的可以點個贊,或者轉發一下噢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章