Spring Java Configuration之@Configuration和@Bean

Spring Java Configuration是指用配置类来代替spring中的xml配置文件,

总的来说@Configuration相当于xml中的<beans>标签,@Bean相当于xml中的<bean>标签。

@Configuration没什么好说的,表示声明下面要配置bean了。

具体说下@Bean,在官方的文档中有下面一段话,并举了一个例子:

declare a bean, simply annotate a method with the @Bean annotation. WhenJavaConfig encounters such a method, it will execute that method and registerthe return value as a bean within aBeanFactory. By default, thebean name will be the same as the method name (seebean naming for details on how to customize this behavior). Thefollowing is a simple example of a@Bean method declaration:

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}
                

For comparison sake, the configuration above is exactly equivalent to thefollowing Spring XML:

<beans>
    <bean name="transferService" class="com.acme.TransferServiceImpl"/>
</beans>
                
其大意是说,@Bean通过注解一个方法来声明一个bean。当JavaConfig遇到此方法时,这个方法会被执行,并且该方法的返回值被被注册到BeanFactory中。默认的情况下,bean的注册名称是方法名称。

后面的两段代码的作用是相同的,只不过一个是java配置类,而另一个是用xml配置的。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值