您的位置: 新闻频道 Java新闻

原创新闻 Spring Java Configuration——用java代码来装配Spring

2008-03-27 by 见习记者 upheart
评论(12) 有1637人浏览 spring

下面是一个典型的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);

 这么做有什么好处呢?

  • 使用纯java代码,不在需要xml
  • 在配置中也可享受OO带来的好处
  • 类型安全对重构也能提供良好的支持
  • 依旧能享受到所有springIoC容器提供的功能

http://feeds.feedburner.com/~r/Interface21TeamBlog/~3/258716055/


来自:Spring Source Team Blog

评论 共 12 条 发表评论

Saro 2008-03-29 10:48
无聊的玩意。
slaser 2008-03-29 10:07
没看出出色的地方。
coolyongzi 2008-03-28 21:47
dataSource
puroc 2008-03-28 20:21
我要换实现类的时候,还得改JAVA代码。耍呢吗?
xinshaoye 2008-03-28 17:11
新鲜,,但感觉不是很实用...还是喜欢xml的
Frederick 2008-03-28 09:46
这个是去年中就退出了的spring-javaconfig项目,和spring2.5的部分功能确实是重合的,但是spring2.5的annotation支持并不整,它只提供了部分功能,比如spring mvc的annotation配置支持等。
而spring-javaconfig项目也不完善,起码它不支持spring2.5。
我正在期待有一个完整的annotation版本的spring出现
bulargy 2008-03-28 09:08
这个东东和spring2.5的annotation貌似是做的同样的事情吧。。。
fujohnwang 2008-03-28 09:01
hehe,spring2.5之后,这个东西还用吗?
heshaoxun 2008-03-27 21:31
真没想到 复古风潮都刮到到这来了! 唉
JavaInActoin 2008-03-27 19:48
轮回,轮回
shanghui_12 2008-03-27 14:17
标记代替配置,很好
Quake Wang 2008-03-27 13:10
这个新特性不错!

发表评论

您还没有登录,请登录后发表评论