此代码在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 {@Beanpublic Bean01 bean01() {return new Bean01();}@Beanpublic 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;}
}