向Spring容器中添加组件

这篇博客介绍了如何在SpringBoot应用中使用@Configuration和@Bean注解来添加和配置组件。@Configuration标记类作为配置源,替代传统的XML配置文件。而@Bean注解用于方法上,表示该方法将返回一个要注册到Spring容器的对象。通过@Scope可以指定Bean的作用域,如singleton或prototype。此外,@Description可以添加Bean的描述。示例中创建了一个名为'Child'的Bean,设置其为单例,并提供了详细的描述和初始化信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何向Spring容器中添加组件
SpringBoot推荐使用@Configuration+@Bean
@configuration 用在类上方,声明这个类是一个spring配置类,执行的功能是代替spring的配置文
件,相当与spring.xml中的 标签
@Bean 用在方法上方,@bean一般与@configuration配合使用,用在@configuration类中的获取实例
的方法上方。相当于spring.xml中的 标签
@Bean 常用参数:
name/value :用于指定Bean的名称,可以指定多个。如果省略不写,bean的名称就是方法名称。
@Bean 常搭配的注解
@Scope(“value”) :用于指定bean的Scope 值可以为 prototype singleton(默认) request
session
@Description(“value”) :指定Bean的描述 可以看作是一种注释
package com.gx.springbootdemoinitializr;
import com.gx.springbootdemoinitializr.vo.Child;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.annotation.Scope;
@Configuration
public class BeanConfig {
@Bean //name(value) 用于指定Bean的名称,可以指定多个。如果省略不写,bean的名称就是方法
名称。
@Scope(“singleton”)//指定bean的Scope 值可以为 prototype singleton(默认)
request session
@Description(“这是描述”)//指定Bean的描述 可以看作是一种注释
public Child mChild(){
Child child=new Child();
child.setName(“杰克”);
child.setAge(10);
return child;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值