常见的Bean工厂后置处理器

此代码在jdk11上测试通过,SpringBoot版本为2.7.14

1.上代码

导入坐标

<dependencies>
    <!-- spring数据坐标 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.4</version>
    </dependency>
    
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.16</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

1.测试类代码

public class Dome05Application {
    public static void main(String[] args) {
        GenericApplicationContext genericApplicationContext = new GenericApplicationContext();
        genericApplicationContext.registerBean("config", Config.class);
        // Bean工厂后置处理器
        // 可以识别@ComponentScan,@Been,@Import等注解
        genericApplicationContext.registerBean(ConfigurationClassPostProcessor.class);
        // 这个是解析@MapperScanner注解
        // genericApplicationContext.registerBean(MapperScannerConfigurer.class);
        genericApplicationContext.refresh();

        for (String beanDefinitionName : genericApplicationContext.getBeanDefinitionNames()) {

            System.out.println(beanDefinitionName);
        }
        genericApplicationContext.close();
    }
}

2.创建Bean01

public class Bean01 {

}

3.创建ComponentBean

@Component
public class ComponentBean {
    public ComponentBean() {
        System.out.println("ComponentBean 构造方法====被Spring加载了");
    }
}

4.创建配置类

@Configuration
@ComponentScan("com.andy.xxx.xxx")  // 第三段代码ComponentBean 所在的包
public class Config {

    @Bean
    public Bean01 bean01() {
        return new Bean01();
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(initMethod = "init")
    public DruidDataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/study_test");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        return druidDataSource;
    }
}

2.运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值