SpringBoot@Configuration使用总结

简介: 被@Configuration标注的类视为Spring配置类,等同于XML配置文件,通过@Bean定义Bean。结合AnnotationConfigApplicationContext可启动IOC容器,加载并管理所有Bean实例,包括配置类自身,实现注解驱动的Spring应用上下文。

被@Configuration标注的类视为Spring配置类,等同于XML配置文件。通过@Bean注册Bean,结合AnnotationConfigApplicationContext可启动IOC容器,加载并管理Bean实例,包括配置类自身。

被 @Configuration 标注的类,会被 Spring 的IOC容器认定为配置类。
一个被 @Configuration 标注的类,相当于一个 applicationContext.xml 的配置文件。

例如:声明一个类,并标注 @Configuration 注解:
@Configuration
public class ConfigurationDemo {
@Bean
public Date currentDate() {
return new Date();
}
}

上述注册Bean的方式类比于xml:

之后使用注解启动方式,初始化一个IOC容器,并打印IOC容器中的所有bean的name:

public class MainApp {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
Stream.of(beanDefinitionNames).forEach(System.out::println);
}
}

输出结果:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
configurationDemo
currentDate

可以发现组件,以及配置类本身被成功加载。

相关文章
|
Java 容器 Spring
springboot中的@Configuration详解~
springboot中的@Configuration详解~
635 0
|
Java 开发者 Spring
深入理解 Spring Boot 中的 @EnableAutoConfiguration 注解:概念与实践
【4月更文挑战第21天】在 Spring Boot 项目中,@EnableAutoConfiguration 注解是实现自动配置的核心,它可以根据项目的依赖和配置,自动地配置 Spring 应用程序中的 Bean
768 3
|
存储 Java 关系型数据库
MyBatisPlus中的TypeHandler | 自定义字段类型转换Handler
MyBatisPlus中的TypeHandler | 自定义字段类型转换Handler
2856 0
|
Java BI 调度
Java Spring的定时任务的配置和使用
遵循上述步骤,你就可以在Spring应用中轻松地配置和使用定时任务,满足各种定时处理需求。
1078 2
|
关系型数据库 MySQL 数据库
同一台电脑安装两个不同版本的mysql。简单暴力有效
这篇文章介绍了在同一台电脑上安装并配置两个不同版本的MySQL数据库的过程,包括修改端口号、配置服务、修改连接端口和测试连接情况,以确保不同版本的MySQL能够正常运行而不相互干扰。
同一台电脑安装两个不同版本的mysql。简单暴力有效
|
JavaScript
request to https://registry.npm.taobao.org/cnpm failed, reason: certificate has expired
request to https://registry.npm.taobao.org/cnpm failed, reason: certificate has expired
1680 2
解析Spring Boot中的配置文件与外部化配置
解析Spring Boot中的配置文件与外部化配置
|
SQL Java 数据库连接
Mybatis中@Param的用法和作用
Mybatis中@Param的用法和作用
971 11
|
存储 安全 Java
什么是 PasswordEncoder?
【8月更文挑战第21天】
968 0
SpringMVC拦截器的介绍,拦截器的基本实现,拦截器链配置
SpringMVC拦截器的介绍,拦截器的基本实现,拦截器链配置
610 2

热门文章

最新文章