1. 程式人生 > >@ImportResource和@Bean註解詳解,超詳細

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

@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);
	}
}

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,簡單明瞭的結束本編部落格,希望看明白的可以點個贊,或者轉發一下噢