常见的Bean工厂后置处理器

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

1.上代码

导入坐标

<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-restartifactId>
    dependency>
    
    <dependency>
        <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-boot-starterartifactId>
        <version>3.5.4version>
    dependency>
    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druid-spring-boot-starterartifactId>
        <version>1.2.16version>
    dependency>
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.33version>
    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.运行结果

常见的Bean工厂后置处理器_第1张图片

你可能感兴趣的:(Spring,java,spring)