spring的注解(1): @Configuration,@Bean,@Component,

本文详细解释了Spring框架中@Configuration和@Bean注解的使用方法及区别。介绍了@Bean如何定义bean实例,以及@Configuration如何组织这些bean定义。同时对比了@Bean在不同上下文中的行为表现。

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

@Configuration和@Bean

@Configuration 相当于<beans> 可以用在类,接口(包括注解类型),或者枚举声明上
@Bean 相当于<bean>,这个只能用在方法或者注解类型声明上
所以

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

就相当于

<beans>
    <bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>

@Configuration和@Component的区别

在spring-framework的文档里写了

Full @Configuration vs 'lite' @Beans mode?
When @Bean methods are declared within classes that are not annotated with @Configuration
they are referred to as being processed in a 'lite' mode. For example, bean methods declared in
a @Component or even in a plain old class will be considered 'lite'.
Unlike full @Configuration, lite @Bean methods cannot easily declare inter-bean dependencies.
Usually one @Bean method should not invoke another @Bean method when operating in 'lite' mode.
Only using @Bean methods within @Configuration classes is a recommended approach of
ensuring that 'full' mode is always used. This will prevent the same @Bean method from accidentally
being invoked multiple times and helps to reduce subtle bugs that can be hard to track down when
operating in 'lite' mode. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值