在这篇文章中,我们将结合实例讨论如何使用Spring @Import
注解。
@Import
注解表示要导入一个或多个@Configuration类。@Import
注解可以在类级别上声明,也可以作为元注解。@Import
注解的一个内部实现。如果需要导入XML或其他非@Configuration
的bean定义资源,请使用@ImportResource注解代替。例如,如果你想加载config.properties
文件,那么你可以使用@ImportResource注解来加载各自的属性文件。
在基于Spring XML的配置中,我们使用一个**<import />**元素来加载多个Spring Bean配置文件。
例如。
<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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="common/spring-common.xml"/>
<import resource="dao/spring-dao.xml"/>
<import resource="beans/spring-beans.xml"/>
</beans>
Spring提供了另一种@Import
注解,允许从另一个配置类中加载@Bean定义。
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
现在,在实例化上下文时不需要同时指定ConfigA
class和ConfigB
class,只需要明确提供e1d9d1即可。
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}
@Import
注解也可以用来从多个配置类文件中加载@Bean的。
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
@Configuration
public class ConfigC {
@Bean
public C c() {
return new C();
}
}
@Configuration
@Import(value = {ConfigA.class, ConfigB.class, ConfigC.class})
public class ConfigD {
@Bean
public D d() {
return new D();
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/09/spring-import-annotation-with-example.html
内容来源于网络,如有侵权,请联系作者删除!