Spring Java Configuration之@Configuration和@Bean
2016-09-12 15:24
447 查看
Spring Java Configuration是指用配置类来代替spring中的xml配置文件,
总的来说@Configuration相当于xml中的<beans>标签,@Bean相当于xml中的<bean>标签。
@Configuration没什么好说的,表示声明下面要配置bean了。
具体说下@Bean,在官方的文档中有下面一段话,并举了一个例子:
declare a bean, simply annotate a method with the
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
For comparison sake, the configuration above is exactly equivalent to thefollowing Spring XML:
其大意是说,@Bean通过注解一个方法来声明一个bean。当JavaConfig遇到此方法时,这个方法会被执行,并且该方法的返回值被被注册到BeanFactory中。默认的情况下,bean的注册名称是方法名称。
后面的两段代码的作用是相同的,只不过一个是java配置类,而另一个是用xml配置的。
总的来说@Configuration相当于xml中的<beans>标签,@Bean相当于xml中的<bean>标签。
@Configuration没什么好说的,表示声明下面要配置bean了。
具体说下@Bean,在官方的文档中有下面一段话,并举了一个例子:
declare a bean, simply annotate a method with the
@Beanannotation. WhenJavaConfig encounters such a method, it will execute that method and registerthe return value as a bean within a
BeanFactory. 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
@Beanmethod 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配置的。
相关文章推荐
- 解读ASP.NET 5 & MVC6系列教程(5):Configuration配置信息管理
- Spring Bean基本管理实例详解
- Spring中多配置文件及引用其他bean的方式
- 详解Spring Boot Junit单元测试
- 详解Spring Boot 集成Shiro和CAS
- 解析Java中如何获取Spring中配置的bean
- Java中BEAN与EJB的区别浅析
- spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制
- 深入解析Java的Spring框架中bean的依赖注入
- 浅谈spring容器中bean的初始化
- Java中Spring获取bean方法小结
- 详解Spring Boot 使用Java代码创建Bean并注册到Spring中
- 详解Java的Spring框架中bean的定义以及生命周期
- 详解Java的Spring框架中bean的注入集合
- Java的Spring框架中bean的继承与内部bean的注入
- Java类获取Spring中bean的5种方式
- Spring boot remote shell 自定义命令 应用篇
- 深入SpringBoot:自定义Endpoint
- 各种概念POJO、JAVABEAN、DAO、DTO、PO、VO、BO、SSH、EJB
- 让Spring Controller 的方法基本数据类型参数支持Bean Validation