Translate Spring XML configuration to Java config

By | January 12, 2018
Questions:

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" />
 </http> 

 <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

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

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.

Answers:

You can’t translate XML configurations with custom namespaces (such as http://www.springframework.org/schema/security). However, you can mix XML configurations with Java-based using @ImportResource

Questions:
Answers:

Follow the JavaConfig project documentation.

Questions:
Answers:

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 *