一:在SpringBoot 啓動類上加 @ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效
Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上
@ImportResource(locations = {"classpath:beans.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.atguigu.springboot.service.HelloService"> </bean>
</beans>
SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式
二:使用全註解的方式 (推薦)
1、配置類@Confifiguration------>Spring配置文件
2、使用@Bean給容器中添加組件
/*** @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件 ** 在配置文件中用<bean><bean/>標籤添加組件 **/
@Configuration
public class MyAppConfig {
//將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("配置類@Bean給容器中添加組件了...");
return new HelloService();
}
}