SpringBoot-容器にBeanを登録するための様々な方法
6734 ワード
要約
Spring容器にBeanを登録するには様々な方法がありますが、ここでは以下のいくつかを紹介します.
Spring容器は@ComponentScanで構成されたパッケージパスをスキャンして、マーク@Component注解の種類を見つけてSpring容器に入れます.
効果はXMLプロファイルの
に相当します.一般的な属性名
タイプ
説明
include Filters
Filter[]
スキャン導入タイプのフィルタルールを指定します.
exclude Filters
Filter[]
スキャン排除タイプのフィルタルールを指定します.
java 8の次のクラスは複数の@ComponentScanスキャン規則をマークすることができます.
@Component説明
よくある相続:-@Configration:標識類は配置類で、よく@ComponentScanまたは@Bean注釈と一緒に使用します.-@Controller-@Repository-@Service
@ビーンでビーン登録
方法としてマークし、方法の戻り値をSpring容器に登録します.種類は戻り値タイプで、idはデフォルトではメソッド名です.
効果はXMLプロファイルの
に相当します.@ImportでBenを登録します.
//
@Import({ ImportTest.class })
public class RegistryBean {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(RegistryBean.class, args);
String[] beanNames = context.getBeanDefinitionNames();
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
public class ImportTest {
}
public class ImportSelectorTest implements ImportSelector {
// ImportSelector
// Spring @Import ,
// ,Spring
// : null
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//
return new String[] { ImportBeanTest.class.getName() };
}
}
public class ImportBeanTest {
}
起動クラスの注釈を同時に修正する@Import({ ImportTest.class })
は@Import({ ImportTest.class,ImportSelectorTest .class })
である.public class ImportBeanDefinitionRegistrarTest implements ImportBeanDefinitionRegistrar {
// ImportBeanDefinitionRegistrar
// Spring @Import Bean
// Spring Bean Bean
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// Bean
RootBeanDefinition beanDefinition = new RootBeanDefinition(String.class);
registry.registerBeanDefinition("ImportBeanDefinitionRegistrar ", beanDefinition);
}
}
起動クラスの注釈を同時に修正する@Import({ ImportTest.class })
は@Import({ ImportTest.class,ImportSelectorTest.class, ImportBeanDefinitionRegistrarTest.class })
である.org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
registryBean
org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
com.ly.bean.ImportTest
com.ly.bean.ImportBeanTest
ImportBeanDefinitionRegistrar
出力結果はSpring容器の全部のbeanの名前です.一番下の3行は以上の3つの方法で登録したbeanコンポーネントです.