步驟一:建立配置類
@Configuration :指明目前是一個配置類;就是來替代目前的spring配置檔案的
用來替換在配置檔案中用的<bean></bean>标簽添加元件
注意: “helloService2”方法名就是表示該bean對象的名稱
如果想要改變bean對象的名稱,可以在給@Bean添加value值
package com.liuchao.config;
import com.liuchao.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration :指明目前是一個配置類;就是來替代目前的spring配置檔案的
* 替換在配置檔案中用的<bean></bean>标簽添加元件
*/
@Configuration
public class MyAppConfig {
/**
* 注意: “helloService2”方法名就是表示該bean對象的名稱
* 如果想要改變bean對象的名稱,可以在給@Bean添加value值
* @return
*/
@Bean("helloService")
public HelloService helloService2(){
System.err.println("配置類@Bean給容器添加元件了");
return new HelloService();
}
}
測試:使用測試類測試結果
package com.liuchao.config;
import com.liuchao.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration :指明目前是一個配置類;就是來替代目前的spring配置檔案的
* 替換在配置檔案中用的<bean></bean>标簽添加元件
*/
@Configuration
public class MyAppConfig {
/**
* 注意: “helloService2”方法名就是表示該bean對象的名稱
* 如果想要改變bean對象的名稱,可以在給@Bean添加value值
* @return
*/
@Bean("helloService")
public HelloService helloService2(){
System.err.println("配置類@Bean給容器添加元件了");
return new HelloService();
}
}