Spring学习笔记-06. 如何与Spring集成

全局组件初始化

对于组件的全局的初始化,可以使用前面所说的ImportBeanDefinitionRegistrar这个方法来指定初始化方法,以开源的队列QMQ的源码为例:

@EnableQmq实现方式

1
2
3
4
5
6
7
8
9
10
11
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(QmqConsumerRegister.class)
public @interface EnableQmq {

String appCode();

String metaServer();
}

其中QmqConsumerRegister实现代码如下

1
2
3
4
5
6
7
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
...
}



Spring在扫描包的时候,会自动的运行registerBeanDefinitions中的方法,实现组件初始化。

单实体使用

利用bean的生命周期可以优雅的实现,其中 @PostConstruct和@PreDestroy写法更容易,也比较好控制,缺点就是需要找到的对应的入口,对于源码阅读不是很友好。

Spring学习笔记-06. 如何与Spring集成

http://blog.laofu.online/2020/01/25/2020-01-25-Spring-importBean/

作者

付威

发布于

2020-01-25

更新于

2025-04-16

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×