

Spring MVC Controller
handle each and every request. When a request comes to spring, it will send that request to the particulate controller based on request mapping. But sometimes we require initing some data only once during the life cycle of Controller
. Spring providesPostConstruct
annotation using that we can archive init of data only once in the life cycle of controller. @PostConstruct
is part of Spring MVC so it will work spring boot also while configuring Spring MVC with spring boot.
The method which has been written with @PostConstruct
will does not return any data. The return type is void
and also do not accept any arguments. Purpose of @PostConstruct
as under:
- Initialize data
- Perform operation that wants to require only one time of Controller life cycle.
Here is Spring MVC @PostConstruct Example:
Here is an example of init SimpleDateFormat using @PostConstruct
so Only SimpleDateFormat object will be created and the same object will be used for all request.
package com.javadeveloperzone.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Java Developer Zone on 19-07-2017. */ @Controller public class SpringBootExampleController { private static SimpleDateFormat dt; @PostConstruct protected void init() { System.out.println("It will called only one time in controller life cycle."); dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("Date init successfully.."); } @GetMapping("/getForm") @ResponseBody public String SpringBootHello() { return dt.format(new Date()); } }
Output
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2017-08-19 10:56:47.037 INFO 104060 --- [ main] com.javadeveloperzone.SpringBootConfig : Starting SpringBootConfig on Mahesh with PID 104060 (F:\extrawork\spring-boot\spring-boot-initbinder-example\target\classes started by Lenovo in F:\extrawork\spring-boot\spring-boot-initbinder-example) 2017-08-19 10:56:47.041 INFO 104060 --- [ main] com.javadeveloperzone.SpringBootConfig : No active profile set, falling back to default profiles: default 2017-08-19 10:56:47.116 INFO 104060 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1b26f7b2: startup date [Sat Aug 19 10:56:47 IST 2017]; root of context hierarchy 2017-08-19 10:56:49.334 INFO 104060 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2017-08-19 10:56:49.350 INFO 104060 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-08-19 10:56:49.352 INFO 104060 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2017-08-19 10:56:49.471 INFO 104060 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-08-19 10:56:49.471 INFO 104060 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2359 ms 2017-08-19 10:56:49.633 INFO 104060 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-08-19 10:56:49.638 INFO 104060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] It will called only one time in controller life cycle. Date init successfully.. 2017-08-19 10:56:49.815 INFO 104060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getForm],methods=[GET]}" onto public java.lang.String com.javadeveloperzone.controller.SpringBootExampleController.SpringBootHello() 2017-08-19 10:56:49.829 INFO 104060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2017-08-19 10:56:49.830 INFO 104060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2017-08-19 10:56:49.963 INFO 104060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1b26f7b2: startup date [Sat Aug 19 10:56:47 IST 2017]; root of context hierarchy 2017-08-19 10:56:50.366 INFO 104060 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-08-19 10:56:50.424 INFO 104060 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2017-08-19 10:56:50.429 INFO 104060 --- [ main] com.javadeveloperzone.SpringBootConfig : Started SpringBootConfig in 3.755 seconds (JVM running for 4.409)