Spring AnnotationConfigApplicationContext 教程展示了如何在 Spring 应用中使用 AnnotationConfigApplicationContext。
Spring 是流行的 Java 应用框架。
AnnotationConfigApplicationContext
AnnotationConfigApplicationContext是一个独立的应用上下文,它接受带注释的类作为输入。 例如@Configuration或@Component。 可以使用scan()查找 Bean,也可以使用register()注册 Bean。
Spring AnnotationConfigApplicationContext示例
以下示例使用AnnotationConfigApplicationContext来构建独立的 Spring 应用。 它有一个 Spring bean DateTimeService,位于scan()中。
pom.mxlsrc├───main│ ├───java│ │ └───com│ │ └───zetcode│ │ │ Application.java│ │ └───bean│ │ DateTimeService.java│ └───resources│ logback.xml└───test └───java
这是项目结构。
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>annotappctx</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <spring-version>5.1.3.RELEASE</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>{spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>{spring-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</version> <configuration> <mainClass>com.zetcode.Application</mainClass> </configuration> </plugin> </plugins> </build></project>这是我们 Spring 应用的 Maven 构建文件。
resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?><configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root></configuration>这是 Logback 配置文件。
com/zetcode/bean/DateTimeService.java
package com.zetcode.bean;import org.springframework.stereotype.Service;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;@Servicepublic class DateTimeService { public LocalDate getDate() { return LocalDate.now(); } public LocalTime getTime() { return LocalTime.now(); } public LocalDateTime getDateTime() { return LocalDateTime.now(); }}DateTimeService是提供数据和时间服务的服务类。 它以@Service构造型装饰,这使它在扫描过程中被检测到。
com/zetcode/Application.java
package com.zetcode;import com.zetcode.bean.DateTimeService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.stereotype.Component;@Componentpublic class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); @Autowired private DateTimeService dateTimeService; public static void main(String[] args) { var ctx = new AnnotationConfigApplicationContext(); ctx.scan("com.zetcode"); ctx.refresh(); var bean = ctx.getBean(Application.class); bean.run(); ctx.close(); } public void run() { logger.info("Current time: {}", dateTimeService.getTime()); logger.info("Current date: {}", dateTimeService.getDate()); logger.info("Current datetime: {}", dateTimeService.getDateTime()); }}我们设置了应用并注入了DateTimeService。 我们称这三种服务方法。
@Componentpublic class Application {Application也是用原型装饰,这次是@Component。 Spring 也会检测到它。 我们需要调用其run()方法以超出静态上下文。
@Autowiredprivate DateTimeService dateTimeService;
服务类注入@Autowired。
var ctx = new AnnotationConfigApplicationContext();ctx.scan("com.zetcode");ctx.refresh();创建一个新的AnnotationConfigApplicationContext。 scan()方法扫描com.zetcode包及其子包中的带注释的类,以生成 bean。 我们需要调用refresh()方法来完成该过程。
public void run() { logger.info("Current time: {}", dateTimeService.getTime()); logger.info("Current date: {}", dateTimeService.getDate()); logger.info("Current datetime: {}", dateTimeService.getDateTime());}我们获取当前日期,时间和日期时间。
$ mvn package$ mvn -q exec:java19:25:12.842 INFO com.zetcode.Application - Current time: 19:25:12.84263920019:25:12.842 INFO com.zetcode.Application - Current date: 2019-01-0519:25:12.842 INFO com.zetcode.Application - Current datetime: 2019-01-05T19:25:12.842639200
我们运行该应用。
在本教程中,我们使用AnnotationConfigApplicationContext创建了一个新的独立 Spring 应用。
