Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate Spring XML configuration to Java config

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.

like image 977
deamon Avatar asked Feb 10 '10 14:02

deamon


3 Answers

Follow the JavaConfig project documentation.

like image 94
Teja Kantamneni Avatar answered Oct 17 '22 04:10

Teja Kantamneni


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.

like image 40
Aaron Digulla Avatar answered Oct 17 '22 04:10

Aaron Digulla


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

like image 26
axtavt Avatar answered Oct 17 '22 04:10

axtavt