Spring Boot recommends Java-based configuration. However, it is possible to load beans from XML sources.
The best practice is to put all configuration in a single class. Usually the class with main
method is considered best to put all configuration and is annotated with @Configuration
.
Additional configuration resources from XML can be imported using @ImportResource
annotation.
Example
Let us now see this with the help of an example. Following is the class with main
method. Note the use of @ImportResource
annotation used to load configuration from beans.xml file which exists in classpath.
package com.learnitweb.XMLImportDemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; @SpringBootApplication @ImportResource("classpath:beans.xml") public class XmlImportDemoApplication { public static void main(String[] args) { SpringApplication.run(XmlImportDemoApplication.class, args); } }
Following is the beans.xml
file which is in classpath of our application.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="employee" class="com.learnitweb.XMLImportDemo.bean.Employee"> </bean> </beans>
To check if the bean is loaded from XML file, we’ll create a simple controller and use it to return the Employee
.
package com.learnitweb.XMLImportDemo.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.learnitweb.XMLImportDemo.bean.Employee; @RestController public class TestController { @Autowired Employee employee; @RequestMapping(value = "/test", method = RequestMethod.GET) public Employee getCoupon() { return employee; } }
Following is the code of Employee
class:
package com.learnitweb.XMLImportDemo.bean; public class Employee { String name = "John"; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Employee [name=" + name + "]"; } }
We can access the application by accessing http://localhost:8080/test
. The output will be:
{"name":"John"}
Conclusion
In this short tutorial, we discussed how to XML configuration in Spring Boot. However, we should avoid this as Spring Boot recommends Java-based configuration. So we should do this only when it is absolute necessary.