For example, the company uses the bean.xml file to generate configuration beans, but you want to continue to reuse bean.xml to save trouble, and @ImportResource is here.
1. Simple demo
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...">
<bean id="haha" class="com.lun.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.lun.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
Instructions:
@configuration
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}
Test class:
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true
}
2. Detailed explanation
@ImportResource
Is a Spring annotation for importing XML configuration files in Java configuration classes. By using @ImportResource
annotations, you can introduce beans and configurations defined in XML configuration files into your application.
The following is @ImportResource
an example of importing a Spring configuration file using annotations:
- Create an XML configuration file, eg
applicationContext.xml
, that contains your bean definitions and other configuration.
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="exampleBean" class="com.example.ExampleBean">
<!-- bean配置 -->
</bean>
</beans>
@ImportResource
2. Import the XML configuration file using annotations in your Java configuration class .
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
// 配置类代码
}
In the example above, I AppConfig
used @ImportResource
annotations on the configuration class and specified the classpath of the XML configuration files that need to be imported.
This way, when your application starts, the beans and configuration defined in the XML configuration file will be loaded and applied.
It should be noted that it is recommended to use Java-based configuration methods (such as usage @Configuration
and @Bean
annotation) instead of XML configuration files to obtain better type safety and compile-time checking. @ImportResource
Use annotations to import XML configuration files only if necessary .