Spring Boot @PostConstruct教程显示了如何在 Spring 应用中使用@PostConstruct注解。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
@PostConstruct
@PostConstruct是在依赖注入完成以执行任何初始化之后需要执行的方法上使用的注解。
Spring Boot @PostConstruct示例
以下应用演示了@PostConstruct的用法。 它使用注解创建两个日志方法,在初始化它们的 bean 之后调用它们。 这些消息在应用运行后显示。 应用本身向客户端发送一条消息。 从配置文件中读取文本消息。
$ tree.├── pom.xml└── src├── main│ ├── java│ │ └── com│ │ └── zetcode│ │ ├── Application.java│ │ ├── controller│ │ │ └── MyController.java│ │ └── service│ │ ├── IMessageService.java│ │ └── MessageService.java│ └── resources│ ├── application.properties│ └── static│ └── index.html└── 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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zetcode</groupId><artifactId>SpringBootPostConstruct</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
这是 Maven pom.xml文件。 spring-boot-starter-parent是父 POM,它为使用 Maven 构建的应用提供依赖关系和插件管理。 spring-boot-starter-web是使用 Spring MVC 构建 Web(包括 RESTful)应用的入门工具。 它使用 Tomcat 作为默认的嵌入式容器。 spring-boot-maven-plugin将 Spring 应用打包到可执行的 JAR 或 WAR 归档文件中。
application.properties
my.msg=Hello therespring.main.banner-mode=offlogging.level.org.springframework=ERROR
application.properties是 Spring Boot 中的主要配置文件。 我们设置了一个message属性,该属性将由应用返回给客户端。 我们关闭 Spring 横幅并减少 Spring 框架的日志记录量。
MyController.java
package com.zetcode.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.zetcode.service.IMessageService;import javax.annotation.PostConstruct;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@RestControllerpublic class MyController {private static final Logger logger = LoggerFactory.getLogger(MyController.class);@AutowiredIMessageService messageService;@RequestMapping(value = "/getMessage")public String getMessage() {String message = messageService.getMessage();return message;}@PostConstructpublic void doLog() {logger.info("Info message in MyController");}}
这是MyController。 它向客户端发送一条消息。
@RequestMapping(value = "/getMessage")public String getMessage() {String message = messageService.getMessage();return message;}
从消息服务生成一条消息,并将其返回给客户端。
@PostConstructpublic void doLog() {logger.info("Info message in MyController");}
doLog()方法用@PostConstruct注解修饰。 在初始化MyController bean 之后调用该方法。 它记录一条简单的参考消息。
IMessageService.java
package com.zetcode.service;public interface IMessageService {public String getMessage();}
IMessageService包含getMessage()合约方法。
MessageService.java
package com.zetcode.service;import javax.annotation.PostConstruct;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class MessageService implements IMessageService {private static final Logger logger = LoggerFactory.getLogger(MessageService.class);@Value(value = "${my.msg}")private String message;@Overridepublic String getMessage() {return message;}@PostConstructpublic void doLog() {logger.info("Info message in MessageService");}}
MessageService包含getMessage()方法的实现。
@Value(value = "${my.msg}")private String message;
从带有@Value注解的application.properties文件中读取返回给客户端的消息,并将其设置为message字段。
@Overridepublic String getMessage() {return message;}
getMessage()返回消息字符串。
@PostConstructpublic void doLog() {logger.info("Info message in MessageService");}
MessageService还包含用@PostConstruct装饰的doLog()方法。 在 bean 初始化之后调用它。
index.html
<!DOCTYPE html><html><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="getMessage">Get Message</a></p></body></html>
这是主页。 它包含一个获取消息的链接。
Application.java
package com.zetcode;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
Application是设置 Spring Boot 应用的入口。 @SpringBootApplication注解启用自动配置和组件扫描。
$ mvn -q spring-boot:run...2017-12-14 21:35:30.788 INFO 10665 --- [main] com.zetcode.service.MessageService : Info message in MessageService2017-12-14 21:35:30.791 INFO 10665 --- [main] com.zetcode.controller.MyController : Info message in MyController...
应用运行后,我们可以在控制台上看到这两个日志消息。
在本教程中,我们展示了如何在 Spring 应用中使用@PostConstruct注解。 您可能也对相关教程感兴趣: Java Servlets 教程, Spring Boot @Controller教程, Spring Boot @ExceptionHandler教程, Spring Boot 上传文件, Spring Boot @PathVariable教程, Spring Boot @RequestParam教程, Spring Boot @ResponseBody教程, Java 教程。
