spring配置是用注解还是XML?

Spring从2.5版本开始支持基于注解驱动的配置,那么引入注解是不是就是说基于注解的配置要优于XML的配置呢?
关于这个问题Spring的官方文档也给出了建议:

Are annotations better than XML for configuring Spring?

The introduction of annotation-based configurations raised the question of whether this approach is ‘better’ than XML. The short answer is it depends. The long answer is that each approach has its pros and cons, and usually it is up to the developer to decide which strategy suits them better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control

大意是说,没有哪种配置更好的说法,各有各的特别而已。基于注解的配置优点是更短、更简洁,缺点是配置嵌入到各个文件中,比较分散不易于管理。而XML配置优点是配置比较集中、方便管理,缺点是配置冗长、不够简洁。
你可以根据自己的情况来选择使用注解或者XML配置,Spring也支持两种配置同时使用,需要注意的是,注解的注入是在XML之前执行的,所以如果同时使用注解和XML注入同一个属性,XML会覆盖掉注解的注入

欢迎关注Java天堂公众号,专注于分享Java相关技术

spring配置是用注解还是XML?_第1张图片

你可能感兴趣的:(spring)