Spring Boot GenericApplicationContext 教程展示了如何在 Spring 应用中使用GenericApplicationContext
。 在示例中,我们创建一个 Spring Boot 控制台应用。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
GenericApplicationContext
GenericApplicationContext
是ApplicationContext
的实现,它不采用特定的 bean 定义格式; 例如 XML 或注解。
Spring Boot GenericApplicationContext
示例
在以下应用中,我们创建一个GenericApplicationContext
,并使用上下文的registerBean()
方法注册一个新 bean。 稍后,我们使用getBean()
从应用上下文中检索 bean。
pom.xml
这是 Maven pom.xml
文件。 spring-boot-starter-parent
是父 POM,它为使用 Maven 构建的应用提供依赖关系和插件管理。 spring-boot-starter
是一个核心启动器,包括自动配置支持,日志记录和 YAML。 spring-boot-starter-test
在 Spring 中增加了测试支持。 spring-boot-maven-plugin
将 Spring 应用打包到可执行的 JAR 或 WAR 归档文件中。
application.properties
application.properties
是 Spring Boot 中的主要配置文件。 我们关闭 Spring 横幅,减少仅记录错误的错误,并设置控制台记录模式。
TimeService.java
TimeService
包含一个返回当前日期和时间的简单方法。 该服务类将在我们的通用应用上下文中注册。
MyApplication.java
MyApplication
是设置 Spring Boot 应用的入口。 @SpringBootApplication
注解启用自动配置和组件扫描。 它是@Configuration
,@EnableAutoConfiguration
和@ComponentScan
注解的便捷注解。
我们注入GenericApplicationContext
。
使用registerBean()
方法注册了一个新的TimeService
bean。
我们使用getBean()
检索 bean。
最后,我们调用 bean 的getNow()
方法。
MyApplicationTests.java
我们有一个使用TimeService's
getNow()
方法的简单测试。
这次,我们通过给定名称引用 Bean。
我们运行该应用。
在本教程中,我们展示了如何在 Spring 应用中使用GenericApplicationContext
。