Spring5 入门简单应用,使用 AnnotationConfigApplicationContext 上下文

本文将介绍怎样通过 AnnotationConfigApplicationContext 上下文实现简单的 spring 应用。

下面将演示如何通过 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

我们一定不要当三等公民:等下班、等薪水、等退休。
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号