Spring注解解析(@Configuration和@Bean)

本文记录下平时遇到的spring注解,以免时间长了之后自己又忘记了。

 

1. @Configuration和@Bean

在以往的web项目中,我们一般使用xml的形式来配置Spring容器,通过在<beans></beans>标签中添加<bean>来向IOC容器中注入对象。

Spring团队也给出了另外一种注入的方式,那就是通过注解的方式。通过在class上添加@Configuration和在类方法上添加@Bean我们也能往容器中注入对象。


The central artifacts in Spring’s new Java-configuration support are @Configuration-annotated classes and @Bean-annotated methods.


@Bean注解的作用是:通过方法去实例化、配置、初始化一个新的对象,并将其交给IOC容器去管理。@Bean与xml文件中的<bean/>标签的作用完全一样。方法名是<bean>的id,方法的返回值类型就是注入的类的类型。

@Configuration主要是将类变成一个定义bean的资源类。如果这个类里面的方法被@Bean修饰了,调用这些方法能够设定内部的bean之间的依赖关系。原文如下:


Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes let inter-bean dependencies be defined by calling other @Bean methods in the same class. 


@Configuration和@Bean最常用且最简单的结合是:

@Configuration
public class AppConfig {

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

这等价于xml文件中的:

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值