系列二十三、将一个第三方的类配置成bean的方式

一、将一个第三方的类配置成bean的方式

1.1、概述

日常的JavaEE开发中,难免不会遇到需要使用第三方的类的情况,比如:MyBatisPlus、RedisTemplate、DruidDataSource...,这些外部组件是不同的组织或个人提供的,我们为什么可以直接使用呢?这就涉及到了如何将一个第三方的类配置成bean的方式的问题,常见的方式如下:

@Autowired、@Resource、@Bean、@Import(xxx.Class)、@Import(xxxImportBeanDefinitionRegistrar.class)、@Import(xxxBeanDefinitionRegistryPostProcessor.class),下面分别使用代码进行介绍(省略@Autowired、@Resource):

1.2、@Bean

java 复制代码
/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/26 9:50
 * @Description:
 */
@Configuration
@ComponentScan(basePackages = "org.star")
public class MySpringConfig {
 
    /**
     * 方式一:通过@Bean的方式将一个第三方的类注册成bean
     * 优点:能控制bean的创建过程
     * @return
     */
    @Bean
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }
 
}

1.3、@Import(xxx.Class)

java 复制代码
/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/26 9:50
 * @Description: 方式二:通过@Import(第三方类.class)将一个第三方的类注册为bean
 * 缺点:无法干预bean的实例化过程
 */
@Configuration
@ComponentScan(basePackages = "org.star")
@Import(DruidDataSource.class)
public class MySpringConfig {
 
}

1.4、@Import(xxxImportBeanDefinitionRegistrar.class)

参考 系列二十一、Spring中bean的创建顺序 #2.2.7节 中的案例。

1.5、 @Import(xxxBeanDefinitionRegistryPostProcessor.class)

java 复制代码
/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/10/27 18:52
 * @Description:
 */
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
 
    /**
     * 作用:动态注册BeanDefinition
     * 调用时机:IOC加载时注册BeanDefinition的时候会调用
     * @param registry the bean definition registry used by the application context
     * @throws BeansException
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        RootBeanDefinition definition = new RootBeanDefinition(DruidDataSource.class);
        MutablePropertyValues propertyValues = definition.getPropertyValues();
        propertyValues.add("username","admin");
        propertyValues.add("password","admin123456");
        registry.registerBeanDefinition("druidDataSource",definition);
    }
 
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
 
    }
}
相关推荐
Hx_Ma161 天前
SpringMVC返回值
java·开发语言·servlet
Yana.nice1 天前
openssl将证书从p7b转换为crt格式
java·linux
独自破碎E1 天前
【滑动窗口+字符计数数组】LCR_014_字符串的排列
android·java·开发语言
想逃离铁厂的老铁1 天前
Day55 >> 并查集理论基础 + 107、寻找存在的路线
java·服务器
Jack_David1 天前
Java如何生成Jwt之使用Hutool实现Jwt
java·开发语言·jwt
瑞雪兆丰年兮1 天前
[从0开始学Java|第六天]Java方法
java·开发语言
一点技术1 天前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
datalover1 天前
CompletableFuture 使用示例
java·开发语言
RANCE_atttackkk1 天前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
hello 早上好1 天前
03_JVM(Java Virtual Machine)的生命周期
java·开发语言·jvm