스프링 최적화

구글 클라우드에서 애플리케이션 초기화 시간이 길어지면 500 에러가 발생한다. 스프링의 컴포넌트 스캔과 오토와이어드는 초기화 시간을 늘리는 주요 원인이다. 구글 공식 문서의 권고대로 컴포넌트 스캔과 오토 와이어드 대신 빈을 일일이 정의하는 것으로 스프링 설정 파일을 다음과 같이 수정한다.

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>

component-scan 대신 추가한 context:annotation-config는 스프링의 빈 컨테이너가 빈을 등록할 때 빈에 적용된 애너테이션이 그 기능을 하도록 한다. 예를 들어, 빈에 @Controller 애너테이션이 적용되었다면, 해당 빈을 컨트롤러로 등록한다. context:annotation-config도 mvc:annotation-driven 설정이 필요하다.

다음으로 오토 와이어드 기능을 제거한다. GuestbookController에 @Autowired 애너테이션을 제거하고 세터를 추가한다.

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

Guestbook 최종 소스

최종 방명록 예제 소스
개선된 방명록 예제 소스

참고