For many years working with spring, I noticed a funny pattern: in each new version a new way of configuring the context is added. Let's remember how it was:
- In the first spring, the configuration could be written exclusively on xml-e. (ClassPathXmlApplicationContext (“context.xml”))
- In the second (more precisely, from 2.5) it became possible to create a context through annotations. (AnnotationConfigApplicationContext (“package.name”))
- The third spring added a configuration on java. (AnnotationConfigApplicationContext (JavaConfig.class))
- The fourth one has also preserved the tradition and since December 2013 it can be configured using the groove of scripts (GenericGroovyApplicationContext (“context.groovy”))
Consultation and conducting trainings in different companies, I saw a very different attitude to these methods of configuration. Large companies, often living according to the principle “works - don't touch”, still cherish the old xml configurations, continuing to multiply and feed them with new bins. “But we have everything centralized!” - their architects shout, adding a 100,500 thousandth line to the xml-God.
Smaller companies, trying to keep up with the innovation of technology, mercilessly burn old XMLs, rewriting everything they can, to annotations, and what they cannot to Java-config. And they are already rubbing their hands, trying to think of, and where would they now stick the configuration on the grooves.

I saw absolutely funny situations when a junior who is not very well versed in all this mess, duplicated the bins declaration, writing them in the xml-e and through annotations (well, so for sure).
')
And where is the truth? Is as always in the middle?
Let's try to figure it out ...
First, let's compare the bean declaration strategies.
Let's start with the classic XML-a:
<beans....> <bean class="com.inwhite.spring.compare.CoolDaoImpl" id="coolDao"/> <bean id ="coolService" class="com.inwhite.spring.compare.CoolServiceImpl" init-method="init" destroy-method="closeResources" scope="prototype"> <property name="dao" ref="coolDao"/> </bean> </beans>
Now the same, but with the help of annotations
@Repository public class CoolDaoImpl implements CoolDao { @Override public void doCRUD() {
Once more, but with the configuration on Java:
@Configuration public class JavaConfig { @Bean public CoolDao dao(){ return new CoolDaoImpl(); } @Bean(initMethod = "init", destroyMethod = "closeResources") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public CoolService coolService(){ CoolServiceImpl service = new CoolServiceImpl(); service.setDao(dao()); return service; } }
And finally, the same thing on the groove:
beans { coolDao(CoolDaoImpl) coolService(CoolService){bean-> bean.scope = 'prototype' bean.initMethod = 'init' bean.destroyMethod = 'closeResources' } }
If we compare the expended efforts, then annotations are in the lead for this configuration (there are only 6 of them, minus the setter).
But since the configuration of a full-fledged application (and not a separate module), which also includes third-party libraries, cannot be kept only on annotations, it would be more honest to compare between the Groovy, Java and XML configurations. Even without glasses, it is clear that the configuration on the groove is leading in brevity and elegance, but I would like to leave it for a snack. Moreover, it is not yet fully finished.
In the meantime, let's discuss the advantages and disadvantages of what was before Spring 4.

After reading the last line, the harsh critics have probably already made a mark for themselves, they say aha, the author of the article is not aware of Factory Beans, SpEL and any tricky profiles ... But let's be honest, XML has already earned a lot of advantages in this table, and on their background This plus will look far-fetched. SpEL is quite limited, and Factory Beans are not part of XML-a. And honestly, even the most ardent fans of XML would hardly have chosen it as a programming language.
Another question that I often get asked at trainings: “Why not recompile when changing the configuration is a plus? Who will risk on the production to change the implementation of the bins without having banished the tests after this? And all sorts of little things like names, passwords and ports can be simply kept in the files whose contents can also be changed without recompiling. ”
Here it will be appropriate to tell one case from my practice, which can be titled something like this:
How XML with JBoss th party saved
A few years ago, I worked in a single IT company where, for security reasons, programmers could not connect to the work environment via remote access. And after another week of work, we went to rest. We sit in the pub, the time is the beginning of the third morning, the mood is excellent, and suddenly, our support call. Come, says urgently. Production falls.
Common situation? There are many reasons for not wanting to go to work on Friday night ... In my attempts to persuade him to try to solve everything on the phone, he insists that he is only a support and the only thing he can do is dial the phone number of the one who needs to be called. In the end, he nevertheless agreed to read me an exception. The problem turned out to be trivial: one of the web services began to fail, and the bin that addressed it threw out an exeptnn due to which the entire application fell. Apparently, the author of Bina did not expect such an ambush, and the expedition was not caught. And since this did not happen before, QA missed this code in production.
And I knew perfectly well that nothing could be done until Monday, since the web service is not ours, and there is nobody to talk to. But it was impossible to leave everything as it was, on the server there were still many other jobs that could work fine if you throw the problematic bin out of context. I will not go into details, but I am sure that you yourself can think out a similar scenario. The question is how to change the configuration on the phone, talking to a person who does not understand anything in the code.
Fortunately for me, this bin was registered in xml-e. Then the following dialogue took place:
“Go to the comp production, open the JBoss / server / default / deploy folder, find the idi.ear file there and open it. What do you mean, how? Okay, rename it to zip and open it. Great, do you see the META-INF folder there? Does it have applicationContext.xml? Go into it, find a SchedulerFactoryBean there and just below there is a datacarTrigger. Comment out this line. What do you mean, how? It does not matter, erase it. Great, now write it down, close it, rename it back to ear, and turn on the server in a new way. ”
Well and everything, further the happy end. Now imagine that this bin would be registered in the java config ... Apparently you would have to go to work.
You can tell a lot of such stories, and the ability to change the configuration without compiling anything and not building anew is often a big plus. Starting from aspects that need to be turned on, then off, then reconfigured, and ending with delivery-oriented companies that customize the same product for different customers.
Such an architect initially implies that xml will lie outside the archive (war, ear), and where it is easy to reach. And most likely, in companies where such an approach is used, there is an entire ecosystem, honed under such dynamism, with special tests and roller backs.
On the other hand, when it comes to complex configurations that cannot be purely declarative, working with XML becomes extremely inconvenient. All the crutches invented for this even in the first versions of Spring make the configuration very confusing and difficult to maintain.
.
Java configuration has a big advantage in such cases. All bins, settings that require a certain business logic, it is much more correct to write in it. Not to mention the fact that for a Java developer it is much more pleasant to write Java, and not XML.
Another small, but still the advantage of a Java configuration is performance. We all know, since high school, that "reflexion slows down." And bins written in XML-e or using annotations will be created using it. If they are all singletons, then this is not so important: just the bootstrap time will increase slightly. However, if your program constantly creates prototypes, Reflection is not desirable. Well, with the configuration in Java, reflex is simply not used. Beans are created using regular Java code.
The advantage of annotations is that they reduce the configuration. In addition, if each new bin, forcing the developer to run into the config, and something there to edit or append, then in addition to the inconvenience and permanent murgi, there is a chance that someone will accidentally ruin someone else's. In addition, as we well know, if in the first act a gun hangs on the stage ...
That is why, far from every company, architects allow everyone to poke around in the config file and prescribe their bins there, for fear of Krivoruk programmers who do not know what they are doing.
Someone will say, they say, but we do not use annotations at all: yes it is not always convenient, but everything is centralized. Well, here one of two things, either your project is very small, and the cat wept for springing in it, or all this “centralization” does not bring clarity. Huge XML or Java configs, which only a chess grandmaster can understand, ultimately lead to even more confusion.
Results
All of our classes, which should be Spring bins, are declared and set up with annotations, beautifully arranged by package and scanned, as directed by the central configuration.
All bins from third-party libraries, and what needs a complex configuration is defined in the Java config.
And that part of the configuration that needs dynamism is put into XML, which, in addition, can also be stored as an external resource.
Why was it necessary to invent a configuration on Groovy, when even without it there was already a mess? Gruvy, of course, is in fashion today, but is this a reason to add another configuration, increasing confusion? Let's understand what its essence?
Config on Groovy
The idea behind the Groovy configuration is to replace everything except annotations. It has all the advantages of XML - because it is a script, and you can also keep it as an external resource. Moreover, the dynamism can be even more, in potential, changes in the configuration will not require a restart.
On the other hand, it also has all the advantages of a Java config, and moreover, the code on the groove is more concise, more elegant and more powerful.
However, at this stage, it cannot be fully used instead of the Java configuration, because there is no support for namespacs for @EnableAspectJAutoProxy, @EnableAsync, and much more. This, of course, can be solved by setting all the necessary bins in the configuration, but in order not to bother, it is easier for now to leave the Java config. But XML can already be thrown out :)
Feeling the fists clenching from the XML supporters from the last phrase, I propose to arrange a battle.
All optimists who are not afraid of new technologies are invited to the blue corner of the ring; on the contrary, they are trying to implement them in order to move forward and move their company. They will fight for maximum dynamism, for the possibility of developers to do more and easier, for Agile development and for technical innovations.
Realists, taught by bitter experience, who know what will happen when everyone has the power, are invited to the red corner of the ring. These people today appreciate the fact that the configuration on Java is Type Safe, and XML does not give anyone the opportunity to break firewood.
In the meantime, the battle continues, I venture to express my assumption as to how the war against the XML will end. Let's look at the picture again and remember the old movie:

Schwarzenegger, of course, eventually won, but at what price ...
Well, if someone wants to continue the battle live, come to my report:
Spring the Ripper , who wants to seriously improve their skills - come to the
Spring for Seniors training