Java Dependency injection: XML or annotations

后端 未结 10 2244
既然无缘
既然无缘 2020-12-23 09:45

Annotations becoming popular. Spring-3 supports them. CDI depends on them heavily (I can not use CDI with out of annotations, right?)

My question is why

10条回答
  •  死守一世寂寞
    2020-12-23 10:05

    In my opinion, this is more a matter of taste.

    1) In our project (using Spring 3), we want the XML-configuration files to be just that: configuration. If it doesn't need to be configured (from end-user perspective) or some other issue doesn't force it to be done in xml, don't put the bean-definitions/wirings into the XML-configurations, use @Autowired and such.

    2) With Spring, you can use @Qualifier to match a certain implementation of the interface, if multiple exist. Yes, this means you have to name the actual implementations, but I don't mind.

    In our case, using XML for handling all the DI would bloat the XML-configuration files a lot, although it could be done in a separate xml-file (or files), so it's not that valid point ;). As I said, it's a matter of taste and I just think it's easier and more clean to handle the injections via annotations (you can see what services/repositories/whatever something uses just by looking at the class instead of going through the XML-file looking for the bean-declaration).

    Edit: Here's an opinion about @Autowired vs. XML that I completely agree with: Spring @Autowired usage

提交回复
热议问题