Spring Boot @PostConstruct
最后修改时间:2023年7月20日
Spring Boot @PostConstruct 教程展示了如何在 Spring 应用程序中使用 @PostConstruct 注解。
Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级的基于 Spring 的应用程序。
@PostConstruct
@PostConstruct 是一个注解,用于标记需要在依赖注入完成后执行以进行任何初始化的方法。
Spring Boot @PostConstruct 示例
以下应用程序演示了 @PostConstruct 的用法。它使用该注解创建了两个日志方法,在它们的 bean 初始化后被调用。这些消息在应用程序运行后显示。应用程序本身向客户端发送一条消息。文本消息从配置文件中读取。
build.gradle
...
src
├── main
│ ├── java
│ │ └── com
│ │ └── zetcode
│ │ ├── Application.java
│ │ ├── controller
│ │ │ └── MyController.java
│ │ └── service
│ │ ├── IMessageService.java
│ │ └── MessageService.java
│ └── resources
│ ├── application.properties
│ └── static
│ └── index.html
└── test
├── java
└── resources
这是项目结构。
plugins {
id 'org.springframework.boot' version '3.1.1'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'com.zetcode'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
这是 Gradle 构建文件。spring-boot-starter-web 是一个用于构建 Web 应用程序(包括 RESTful 应用程序)的启动器,它使用 Spring MVC。它使用 Tomcat 作为默认的嵌入式容器。
my.msg=Hello there spring.main.banner-mode=off logging.level.org.springframework=ERROR
application.properties 是 Spring Boot 中的主要配置文件。我们设置了一个消息属性,该属性将由应用程序返回给客户端。我们关闭了 Spring 横幅并减少了 Spring 框架的日志记录量。
package com.zetcode.controller;
import com.zetcode.service.IMessageService;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
final IMessageService messageService;
@Autowired
public MyController(IMessageService messageService) {
this.messageService = messageService;
}
@RequestMapping(value = "/message")
public String getMessage() {
return messageService.getMessage();
}
@PostConstruct
public void doLog() {
logger.info("Info message in MyController");
}
}
这是 MyController。它向客户端发送一条消息。
@RequestMapping(value = "/message")
public String getMessage() {
String message = messageService.getMessage();
return message;
}
一条消息从消息服务生成,并返回给客户端。
@PostConstruct
public void doLog() {
logger.info("Info message in MyController");
}
doLog 方法使用 @PostConstruct 注解进行修饰。该方法在 MyController bean 初始化后被调用。它记录一条简单的信息性消息。
package com.zetcode.service;
public interface IMessageService {
String getMessage();
}
IMessageService 包含 getMessage 契约方法。
package com.zetcode.service;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MessageService implements IMessageService {
private static final Logger logger = LoggerFactory.getLogger(MessageService.class);
@Value(value = "${my.msg}")
private String message;
@Override
public String getMessage() {
return message;
}
@PostConstruct
public void doLog() {
logger.info("Info message in MessageService");
}
}
MessageService 包含 getMessage 方法的实现。
@Value(value = "${my.msg}")
private String message;
返回给客户端的消息是从 application.properties 文件中使用 @Value 注解读取的,并设置为 message 字段。
@Override
public String getMessage() {
return message;
}
getMessage 返回消息字符串。
@PostConstruct
public void doLog() {
logger.info("Info message in MessageService");
}
MessageService 还包含使用 @PostConstruct 修饰的 doLog 方法。它在 bean 初始化后被调用。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>
<a href="/message">Get Message</a>
</p>
</body>
</html>
这是主页。它包含一个获取消息的链接。
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application 是设置 Spring Boot 应用程序的入口点。 @SpringBootApplication 注解启用自动配置和组件扫描。
$ ./gradlew bootRun ... ... com.zetcode.service.MessageService : Info message in MessageService ... com.zetcode.controller.MyController : Info message in MyController ...
应用程序运行后,我们可以在控制台上看到这两条日志消息。
在本文中,我们展示了如何在 Spring Boot 应用程序中使用 @PostConstruct 注解。