下面是一个典型的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了:
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容器提供的功能
相关推荐
Spring annotation 样例
在微服务流行的当下,在使用SpringCloud/Springboot框架开发中,AOP使用的...本资源是@Pointcut使用@annotation的方式,结合五种通知Advice实现了打印方法Log的功能。 有任何问题,欢迎大家私信联系我. 作者:天罡gg
NULL 博文链接:https://garrincha.iteye.com/blog/2109688
SpringMVC Spring MyBatis 框架整合 Annotation Maven Project
拦截器 , 过滤器 , 序列化 , @After , @AfterReturning , @AfterThrowing , @annotation , @Around , @Aspect , @Autowired , @Bean , @Before , @Component , @ComponentScan , @ComponentScans , @Configuration ...
详解Spring_3.0基于Annotation的依赖注入实现
Spring Annotation
Spring+mybatis annotation形式 进行增删查改,使用maven容器,配置完整,自己运行多次无问题
使用spring和hibernate的Annotation的小项目,帮助新手理解annotation
详解 Spring 3.0 基于 Annotation 的依赖注入实现。。详解 Spring 3.0 基于 Annotation 的依赖注入实现。。
JSF+Spring+Hibernate(Annotation)的login小实例,建议入门的朋友看看,老鸟就免了,呵呵。环境:SQLSever2000+jdk5.0+spring2.0+hibernate3.2+jsf
SpringMVC Spring Hibernate 框架整合 Annotation Maven Project
Spring IOC Annotation 注入 学习实例
NULL 博文链接:https://bijian1013.iteye.com/blog/2142528
spring项目启动报错,@EnableAsync annotation metadata was not injected日志
spring的Annotation注解.
struts2 spring2.5 hibernate3.0 annotation 整合
Spring_Annotation_AOP
Dwr3+Spring3 全注解 annotation 方式实现