Springbootで@import注記でJavaクラスをインポートしてbeanと宣言する3つの方法
2380 ワード
public class Car1 {
public void say(){
System.out.println("i am car1");
}
}
---
@Configuration
@Import(value = {Car1.class})
public class AutoConfig {
}
---
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AutoConfig.class);
Car1 car1 = context.getBean(Car1.class);
car1.say();
ImportSelector
インターフェースと組み合わせて使用する:このインターフェースを実装し、その中のselectImports
メソッドを書き換え、インポートする必要があるJavaクラスの全限定名からなる文字列配列 public class Car2 {
public void say(){
System.out.println("i am car2");
}
}
---
public class CustomImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
String[] arr = new String[1];
arr[0] = "com.blade.demo.autoConfigure.Car2";
return arr;
}
}
---
@Configuration
@Import(value = {Car1.class, CustomImportSelector.class})
public class AutoConfig {
}
---
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AutoConfig.class);
Car2 car2 = context.getBean(Car2.class);
car2.say();
}
}
ImportBeanDefinitionRegistrar
使用 public class Car3 {
public void say(){
System.out.println("i am car3");
}
}
---
public class CustomImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar{
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(Car3.class);
beanDefinitionRegistry.registerBeanDefinition("car3",beanDefinition);
}
}
---
@Configuration
@Import(value = {Car1.class, CustomImportSelector.class, CustomImportBeanDefinitionRegistrar.class})
public class AutoConfig {
}
---
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AutoConfig.class);
Car3 car3 = context.getBean(Car3.class);
car3.say();
}
}