Import Spring XML files into @Configuration

This is common to mix XML configuration into Spring @Configuration, because developers are used to the XML namespaces. In Spring, you can use @ImportResource to import Spring XML configuration files into @Configuration :

AppConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:/config/spring.xml")
public class AppConfig {

}

Another example

AppConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ AppConfigWeb.class })
@ImportResource("classpath:/config/spring.xml")
public class AppConfig {

}

P.S @ImportResource has been available since Spring 3.0

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Shilan
7 years ago

We have a huge spring xml-based project. We would like to change it to spring boot and it is not easy to change everything to @Beans. Just to be begin with, can I keep our old web.xml as it is if I set packaging to war in pom?
Or web.xml should be converted to Config before we can run spring-boot?

Akash
7 years ago

FileNotFoundException: Could not open ServletContext resource [classpath:/main/webapp/WEB-INF/spring-servlet.xml]

Tried many path combinations for xml file but didnt work.
Please help.

sathish
9 years ago

is there a way to accomlish the same class with Annotations like @Configuration
@Import({ AppConfigWeb.class })
@ImportResource(“classpath:/config/spring.xml”)

using spring2.5.6 ? I know this is available only from spring 3. Please let me know an alternative approach.

James Warner
9 years ago

If you have a project of spring framework whenever you import file code

shruti
10 years ago

hi, I cannot find the Appconfig.java file? where should I create it or find it?

Linus
11 years ago

is there a way to import config in the xml file? i have a dependency project that is spring 4 but is being imported into a Spring 3 project which has XML configuration. The problem is i cannot use autowired beans as the parent project is not aware of those beans for autowiring

mkyong
10 years ago
Reply to  Linus