How to use Spring in Spring Boot applications

If you have Spring applications, using several XML configuration files, you can still integrate them with Spring Boot. Let’s see how in this tutorial.

Importing Spring applications requires basically to import their resources. In the below example, we import the context files using @ImportResource. :

@ImportResource({
  "META-INF/spring/services-context.xml",
  "META-INF/spring/repositories- context.xml"
})
@SpringBootApplication
public class SpringApplication {
  @Autowired TaskRepository task;
  @Autowired ServiceFacade service;
  //More logic...  
}

In order to access the beans, we auto-wire them to the class members. Here is another example which shows how you can re-use existing XML configuration files from the classpath.

@ImportResource("classpath:applicationContext.xml") @Configuration public class XMLConfiguration {
  @Autowired Connection connection;
  //Derived from the applicationContext.xml file. 
  @Bean Database getDatabaseConnection() {
    return connection.getDBConnection();
  }
}

The following code shows how you can reuse your XML in an existing Java configuration class using the ConfigurableApplicationContext. You can also use a main class method to pick up your existing XML file:

public class Application {
  public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext ctx =
        new SpringApplication("/META-INF/spring/integration.xml").run(args);
    System.out.println("Hit Enter to terminate");
    System.in.read();
    ctx.close();
  }
}

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon