下面将演示如何通过 Spring 的 AnnotationConfigApplicationContext 上下文实现类,通过 Java 配置类的方式加载 Spring Bean。
引入 Spring5 依赖,如下:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.29</version> </dependency>
实现一个简单的服务类,该服务类通过 getUUID() 方法返回一个 UUID 字符串。其中,@Component 注解的作用与 @Service 注解是一样的,都是为了声明这个类是一个 Spring Bean。
代码如下:
package com.hxstrive.spring5.hello;
import org.springframework.stereotype.Component;
import java.util.UUID;
/**
* 定义一个服务
* @author hxstrive.com
*/
@Component
public class MyService {
public String getUUID() {
return UUID.randomUUID().toString();
}
}Application 类是一个典型的 Java Application 类,其中 main 方法就是应用执行的入口。下面示例中,AnnotationConfigApplicationContext 类是 Spring 上下文的一种实现,实现了基于 Java 配置类的加载,主要用于管理 Spring bean。Application 类上的 @ComponentScan 注解会自动扫描指定包下全部标有 @Component 的类,并自动注册为 bean,当然也包含 @Component 下的子注解 @Service、@Repository、@Controller 等。
代码如下:
package com.hxstrive.spring5.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* 第一个 Spring5 程序
* @author hxstrive.com
*/
@ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
MyService myService = context.getBean(MyService.class);
System.out.println(myService.getUUID());
}
}运行服务,输出如下:
e3153d06-1799-48a4-b82e-7a6bb1206368