Spring @Configuration用annotation装配spring
来源:互联网 发布:数据结构与算法笔记 编辑:程序博客网 时间:2024/05/18 01:12
下面是一个典型的spring配置文件(application-config.xml):
- <beans>
- <bean id="orderService" class="com.acme.OrderService"/>
- <constructor-arg ref="orderRepository"/>
- </bean>
- <bean id="orderRepository" class="com.acme.OrderRepository"/>
- <constructor-arg ref="dataSource"/>
- </bean>
- </beans>
然后你就可以像这样来使用是bean了:
Java代码
- ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
- OrderService orderService = (OrderService) ctx.getBean("orderService");
现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:
- @Configuration
- public class ApplicationConfig {
- public @Bean OrderService orderService() {
- return new OrderService(orderRepository());
- }
- public @Bean OrderRepository orderRepository() {
- return new OrderRepository(dataSource());
- }
- public @Bean DataSource dataSource() {
- // instantiate and return an new DataSource …
- }
- }
然后你就可以像这样来使用是bean了:
- JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
- OrderService orderService = ctx.getBean(OrderService.class);
这么做有什么好处呢?
1.使用纯java代码,不在需要xml
2.在配置中也可享受OO带来的好处
3.类型安全对重构也能提供良好的支持
4.依旧能享受到所有springIoC容器提供的功能
对于以注解为中心的配置方式,只需使用 @ImportResource 注解引入存在的 XML 即可,如下所示:
@Configuration
@ImportResource(“classpath:/bookstore/config/spring-beans.xml”)
public class MyConfig{
……
}
0 0
- Spring @Configuration用annotation装配spring
- Spring @Configuration用annotation装配spring
- Spring @Configuration用annotation装配spring
- Spring @Configuration用annotation装配spring
- Spring @Configuration用annotation装配spring
- spring annotation 之 自动装配
- Annotation based configuration in Spring
- Spring 基于 annotation 的自动装配
- 模仿 spring IOC Annotation版自动装配
- Spring Java Configuration——用java代码来装配Spring
- spring 装配
- spring装配
- Spring装配
- Spring基于Annotation为dao装配sessionFactory的问题
- (3)Spring study 3 ------- Bean装配 annotation (待续....)
- Spring-Bean之基于注解(Annotation)装配解析
- spring boot Configuration Annotation Proessor not found in classpath
- spring boot Configuration Annotation Proessor not found in classpath
- strstr源码学习,面试用得到
- fibonacci数列的不同实现方法对比(java)
- Android 工具下载集合
- impala数据导入汇总
- 牛客---特殊排序
- Spring @Configuration用annotation装配spring
- spring3+struts2+mybatis3框架整合
- 求有向网中任意一对顶点之间的最短路径 Floyd算法
- 巴斯光年探险阿里聚安全攻防挑战赛!决战12月28日!
- SSL JudgeOnline 1082——导弹拦截
- 点击现实与隐藏,点击其它地方隐藏刚显示的元素
- uboot配置文件mkconfig详解
- JQuery easyui Datagrid 分页事件
- SpringBoot Helloworld 测试 Maven项目