spring boot 中@import 的用法
时间: 2023-12-01 13:04:09 浏览: 31
在Spring Boot中,@Import注解用于导入其他配置类或者配置文件。它的作用是将其他配置类或者配置文件中的bean导入到当前的配置类中。通常情况下,我们可以使用@Import注解来导入以下类型的配置类或者配置文件:
1.其他@Configuration注解标注的配置类
2.@Enable*注解标注的配置类
3.@ImportSelector接口的实现类
4.@ImportBeanDefinitionRegistrar接口的实现类
使用@Import注解的语法如下:
```
@Configuration
@Import({OtherConfig.class, AnotherConfig.class})
public class AppConfig {
// ...
}
```
在上面的例子中,我们使用@Import注解来导入了两个其他的配置类:OtherConfig和AnotherConfig。这些配置类中定义的bean将会被自动注册到当前的配置类中。
除此之外,@Import注解还可以用来动态装配bean,例如:
```
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
@Import(MyImportSelector.class)
public static class MyConfig {}
public static class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[] { "com.example.AnotherBean" };
}
}
}
```
在上面的例子中,我们定义了一个MyBean的bean,并且使用@Import注解来导入了一个实现了ImportSelector接口的MyImportSelector类。这个类会动态地返回一个字符串数组,包含了要导入的bean的类名。在这个例子中,我们导入了另一个名为AnotherBean的bean。