步骤一:创建配置类
@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();
}
}