Spring Optimization

If your application's initialization time exceeds the standard time, you might get a 500 error on Google Cloud. Spring component scans and autowired are the leading causes of increased initialization time. Let's modify the Spring configuration file by defining beans instead of component scans and autowired as recommended by Google's 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 instead of component-scan makes the annotation declared on the bean work when Spring registers beans. For example, Spring registers the bean with @Controller annotation above the class declaration as controller.

The context:annotation-config needs the mvc:annotation-driven to work.

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

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

Final Sources

Final source
improved guestbook source

References