系列二十三、将一个第三方的类配置成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 {
 
    }
}
相关推荐
SimonKing27 分钟前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
CoderYanger38 分钟前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Rain的Java大神之路1 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
蜡笔小谢11 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
唐老板13 小时前
Spring AI 2.0 只支持 Boot 4
java
琳少_16 小时前
java程序设计笔记
java·开发语言·数据库·笔记
考虑考虑16 小时前
记一次@Async生产事故
spring boot·后端·spring
小荷才露尖尖角,早有蜻蜓立上头17 小时前
SpringBoot 定时任务
java·spring boot·后端
Helix25018 小时前
JDK高频报错速查手册:javac不是内部命令、内存溢出、版本不兼容等12类问题解决方法
java·开发语言·内存溢出·java异常处理·jdk版本兼容·jdk报错·javac报错
CoderYanger19 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法