Skip to content

Chapter 4 Demo

David Zemon edited this page Feb 5, 2017 · 3 revisions

Convert to Java Configuration

XML was fun, but the future lies with Java configuration. Java configuration provides a number of benefits, not the least of which is the ability to place breakpoints and use basic IDE shortcuts to determine where a bean is instantiated.

Part 1 - Creating the New Container

  1. Any class annotated with Spring's @Configuration annotation can be used as a Spring configuration file. Many applications at UP (but not all) keep configuration files contained within a single package heirarchy, so create a new Java package and a new class in that package which will be annotated with @Configuration. It is also common practice to suffix these configuration classes with the word Config, such as MainConfig.java.
  • Whenever you are upgrading a legacy project from XML configuration to Java configuration, you'll want to do it in baby steps. The first baby step is to import the entire XML configuration into your Java configuration, without defining any new beans in Java. Use the @ImportResource(...) annotation on the top of the class to provide the path to your XML configuration: "classpath:spring-context.xml".
  • We can now replace the instantiation of ClasspathXmlApplicationContext with AnnotationConfigApplicationContext. The only different (that we care about in this course) between the two classes is that one accepts paths of XML configuration files and the other accepts Class objects for configuration classes.
  • The application should run exactly the same as before.

Part 2 - Move Beans from XML to Java

  1. It's best to convert from XML to Java in a top-down approach. The HumanInterface bean is the top-level of our business logic, so create a bean for that class first. It's dependencies can be injected as parameters to the bean method (in fact, this is one of the only ways possible at the moment).
  • This should be a solid start on converting an XML-based Spring application to Java-based. Confirm that the application still runs.

Clone this wiki locally