Spring Optimization

500 errors occur when application initialization time is long in Google cloud. Spring component scans and autowired are the main causes of increased initialization time. Modify the Spring configuration file by defining beans instead of component scans and autowired as recommended by Google official documentation.

guestbook-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
  <security:global-method-security pre-post-annotations="enabled" />
    
  <mvc:resources mapping="/resources/**" location="/resources/" />

  <mvc:annotation-driven />

  <!-- <context:component-scan base-package="net.java_school.guestbook" /> -->
  <context:annotation-config />

  <bean id="internalResourceViewResolver"
	  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass">
      <value>org.springframework.web.servlet.view.JstlView</value>
    </property>
    <property name="prefix">
      <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
      <value>.jsp</value>
    </property>
  </bean>
  
  <bean id="guestbookController" class="net.java_school.guestbook.GuestbookController">
    <property name="guestbookService" ref="guestbookService" />
  </bean>

  <bean id="guestbookService" class="net.java_school.guestbook.GuestbookServiceImpl" />
  
</beans>

The annotation-config added in place of component-scan allows an annotation declared in a bean to function when a Spring container registers a bean.
For example, if an @Controller annotation is declared in a bean, Spring registers the bean as a controller.
context:annotation-config also needs mvc:annotation-driven configuration.

Remove the @Autowired annotation from the GuestbookController and add the setter as follows.

@Controller
public class GuestbookController {
  
  private GuestbookService guestbookService;
  
  public void setGuestbookService(GuestbookService guestbookService) {
    this.guestbookService = guestbookService;
  }
  
  //.. omit ..
	
}

Final Sources

Final source
improved guestbook source

References