springboot项目使用@Configuration注解的方式注入bean组件

步骤一:创建配置类

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值