springboot的事件

本文详细描述了一个SpringBoot项目的pom.xml配置,涉及依赖管理、启动类、事件类、监听器的实现以及控制器层的使用。展示了如何在SpringBoot应用中创建事件并触发监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2023年12月22日
springboot项目的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>even</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>even</name>
    <description>even</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.7.6</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.example.even.EvenApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

springboot项目的启动类配置

@SpringBootApplication
@EnableAsync
public class EvenApplication {
    public static void main(String[] args) {
        SpringApplication.run(EvenApplication.class, args);
    }
}

事件类

/**
 * @author HK
 */
public class Student extends ApplicationEvent {
    private String name;
    private Integer age;

    public Student(Object source,String name,Integer age) {
        super(source);
        this.age=age;
        this.name=name;
    }
}

监听器两个

/**
 * @author HK
 */
@Component
public class StudentListener1 implements ApplicationListener<Student> {
    @Override
    @Async
    public void onApplicationEvent(Student event) {
        System.out.println("监视器1被触发");
    }
}
/**
 * @author HK
 */
@Component
public class StudentListener2 implements ApplicationListener<Student> {
    @Override
    @Async
    public void onApplicationEvent(Student event) {
        System.out.println("监视器2被触发");
    }
}

发布者1个

/**
 * @author HK
 */
@Component
public class StudentPublisher {
    private final ApplicationContext applicationContext;

    @Autowired
    public StudentPublisher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    public void publish(String message,Integer id) {
        applicationContext.publishEvent(new Student(this, message,id));
    }
}

controller层

/**
 * @author HK
 */
@RestController
@RequestMapping("user")
public class event {
    @Autowired
    private StudentPublisher studentPublisher;

    @GetMapping("/point")
    public void register(String userName, Integer point) {
        studentPublisher.publish(userName, point);
    }

}

访问路径:
在这里插入图片描述

结果在这里插入图片描述
到此结束

### Spring Boot 事件处理机制 #### 定义与发布事件Java Spring Boot 应用程序中,事件驱动架构被广泛应用来实现组件间的松散耦合。为了创建自定义事件,开发者通常会继承 `ApplicationEvent` 类[^2]。 ```java public class CustomEvent extends ApplicationEvent { private String message; public CustomEvent(Object source, String message) { super(source); this.message = message; } public String getMessage() { return message; } } ``` 当需要触发该事件时,可以通过 `applicationContext.publishEvent()` 方法完成: ```java @Autowired private ApplicationContext applicationContext; public void publishCustomEvent(String msg){ CustomEvent customEvent = new CustomEvent(this,msg); applicationContext.publishEvent(customEvent); } ``` #### 注册监听器 对于希望响应特定类型的事件的对象来说,应该实现 `ApplicationListener<E>` 接口,在其中指定要监听的事件类型 E 并重写 onApplicationEvent 方法以定义具体的业务逻辑。 ```java @Component public class CustomEventListener implements ApplicationListener<CustomEvent> { @Override public void onApplicationEvent(CustomEvent event) { System.out.println("Received custom event - " + event.getMessage()); } } ``` 除了上述方法外,还可以利用注解的方式更加简洁地注册监听器。只需给目标类的方法加上 `@EventListener` 即可自动将其标记为某个或某些类型事件的处理器。 ```java @Component public class AnotherCustomEventListener { @EventListener public void handleCustomEvent(CustomEvent event) { System.out.println("@EventListener Received another custom event - " + event.getMessage()); } } ``` 这种基于注解的方式来编写监听器不仅减少了样板代码的数量,而且提高了灵活性和易读性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值