Translate Spring XML configuration to Java config

By | January 12, 2018

I’d like to use Spring with Java configuration, but almost all examples are writte in XML and I don’t know how to translate them to Java. Look at these examples from Spring Security 3:

 <http auto-config='true'>
   <intercept-url pattern="/**" access="ROLE_USER" />

        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />

  <password-encoder hash="sha">
    <salt-source user-property="username"/>

How could this translated to Java config? Or, more generally, how can I translate Spring XML config to Java? There is a little section about Java confing in the Spring reference but it is not that helpful.


You can’t translate XML configurations with custom namespaces (such as However, you can mix XML configurations with Java-based using @ImportResource


Follow the JavaConfig project documentation.


This is probably more simple than you think. Spring isn’t doing any magic. The XML config parser just creates bean definitions and registers them with the bean factory. You can do the same by creating a DefaultListableBeanFactory and registering your bean definitions with it. The main mistake here is to think “gee, I’ll just create the beans and put them in the app context”. This approach doesn’t work because Spring creates beans lazily and the API is built around the idea of a factory that gets called when necessary, not a factory which does all the work at startup.

Here is some example code. Note that this sample needs a lot more lines of code but by defining your own helper methods, you should be able to break this down to something which should be on par with XML.

Also check the source for the Spring unit tests for examples.

Leave a Reply

Your email address will not be published. Required fields are marked *