开发者

Java: is it good practice to define beans in XML?

In a project I'm working on, which is using Spring, I see something that really boggles my mind. Apparently there are unit tests that need beans to work and those beans are created from XML files, containing things like:

<bean class="...ListDTO">
 <constructor-arg>
  <map>
   <entry key="use1key">
    <value>use1value</value>
   </entry>
   <entry key="use2key">
    <value>use2value</value>
   </entry>
  </map>
 </constructor-arg>
 <constructor-arg>
  <map>
   <entry key="nature1key">
    <value>nature1value</value>
   </entry>
   <entry key="nature2key">
    <value>nature2value</value>
   </entry>
  </map>
 </constructor-arg>
 <constructor-arg>
  <value>false</value>
 </constructor-arg>
</bean>

And what did happen? The constructor of the class ...ListDTO changed and hence the bean apparently cannot be created anymore from this (very verbose IMHO) XML.

Can someone explain me why is it good practice (is it really?) to put such thing in an XML instead of Java code? If it was in Java code, as soon as the ...ListDTO would have changed the unit test would have refused to compile (even if the part of the unit test instantiating that bean didn't get executed [for whatever reason]).

Bonus question: is there a way to easily find all these broken "beans in XML" in a project besides running all the unit tests, see which ones are failing and then rinse-and-repeating?

To me it seems a pretty serious issue that you can 开发者_高级运维change a constructor and that the IDE would act as if everything was fine: what is the justification for this? (*)


The idea behind this is that you keep things that differ between environments (development, testing, production) in a central XML configuration file, and by using a different config file, you switch environments.

However, It's definitely not good practice to use bean configuration to define complex test data structures. Someone probably did that while newly enamoured with dependency injection, just because it's possible.


Bonus question: is there a way to easily find all these broken "beans in XML" in a project besides running all the unit tests, see which ones are failing and then rinse-and-repeating?

Spring Tool Suite or the Spring plugin for Eclipse can check that an spring configuration file is correct (has all constructor paramter and do not use unkown setters).


I think you should use the SpringSource tools when working with Spring. You can download it either as stand-alone or as Eclipse plugins:

http://www.springsource.com/developer/sts

http://dist.springsource.com/milestone/TOOLS/update/e3.6

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜