多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Spring Boot `@PostConstruct` > 原文: [http://zetcode.com/springboot/postconstruct/](http://zetcode.com/springboot/postconstruct/) Spring Boot `@PostConstruct`教程显示了如何在 Spring 应用中使用`@PostConstruct`注解。 Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。 ## `@PostConstruct` `@PostConstruct`是在依赖注入完成以执行任何初始化之后需要执行的方法上使用的注解。 ## Spring Boot `@PostConstruct`示例 以下应用演示了`@PostConstruct`的用法。 它使用注解创建两个日志方法,在初始化它们的 bean 之后调用它们。 这些消息在应用运行后显示。 应用本身向客户端发送一条消息。 从配置文件中读取文本消息。 ```java $ 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` ```java <?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 http://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` ```java my.msg=Hello there spring.main.banner-mode=off logging.level.org.springframework=ERROR ``` `application.properties`是 Spring Boot 中的主要配置文件。 我们设置了一个`message`属性,该属性将由应用返回给客户端。 我们关闭 Spring 横幅并减少 Spring 框架的日志记录量。 `MyController.java` ```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; @RestController public class MyController { private static final Logger logger = LoggerFactory.getLogger(MyController.class); @Autowired IMessageService messageService; @RequestMapping(value = "/getMessage") public String getMessage() { String message = messageService.getMessage(); return message; } @PostConstruct public void doLog() { logger.info("Info message in MyController"); } } ``` 这是`MyController`。 它向客户端发送一条消息。 ```java @RequestMapping(value = "/getMessage") public String getMessage() { String message = messageService.getMessage(); return message; } ``` 从消息服务生成一条消息,并将其返回给客户端。 ```java @PostConstruct public void doLog() { logger.info("Info message in MyController"); } ``` `doLog()`方法用`@PostConstruct`注解修饰。 在初始化`MyController` bean 之后调用该方法。 它记录一条简单的参考消息。 `IMessageService.java` ```java package com.zetcode.service; public interface IMessageService { public String getMessage(); } ``` `IMessageService`包含`getMessage()`合约方法。 `MessageService.java` ```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; @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()`方法的实现。 ```java @Value(value = "${my.msg}") private String message; ``` 从带有`@Value`注解的`application.properties`文件中读取返回给客户端的消息,并将其设置为`message`字段。 ```java @Override public String getMessage() { return message; } ``` `getMessage()`返回消息字符串。 ```java @PostConstruct public void doLog() { logger.info("Info message in MessageService"); } ``` `MessageService`还包含用`@PostConstruct`装饰的`doLog()`方法。 在 bean 初始化之后调用它。 `index.html` ```java <!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` ```java 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`注解启用自动配置和组件扫描。 ```java $ mvn -q spring-boot:run ... 2017-12-14 21:35:30.788 INFO 10665 --- [main] com.zetcode.service.MessageService : Info message in MessageService 2017-12-14 21:35:30.791 INFO 10665 --- [main] com.zetcode.controller.MyController : Info message in MyController ... ``` 应用运行后,我们可以在控制台上看到这两个日志消息。 在本教程中,我们展示了如何在 Spring 应用中使用`@PostConstruct`注解。 您可能也对相关教程感兴趣: [Java Servlets 教程](/articles/javaservlet/), [Spring Boot `@Controller`教程](/springboot/controller/), [Spring Boot `@ExceptionHandler`教程](/springboot/exceptionhandler/), [Spring Boot 上传文件](/springboot/uploadfile/), [Spring Boot `@PathVariable`教程](/springboot/pathvariable/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/), [Spring Boot `@ResponseBody`教程](/springboot/responsebody/), [Java 教程](/lang/java/)。