[Spring] Java Config

2024. 7. 6. 22:59BE/Spring

1. Spring 설정 파일을 작성하는 방법

 

Spring 설정 파일을 작성하는 방법은 크게 두 가지다.

 

XML을 사용하는 방법과 Java Config를 사용하는 방법이다.

 

방법 설명 장점 단점
XML XML 파일 안에 bean 객체를 정의하고 의존성 설정 시각적으로 객체 관계 이해 용이 XML 문법 필요, 타이핑 오류 가능
Java Config 설정을 Java 클래스로 작성 타입 안전성, IDE 지원으로 리팩토링 용이 설정 코드와 애플리케이션 코드 섞일 가능성, 복잡성 증가

 

Springboot를 생각하면 Java Config에 익숙해질 필요가 있겠다.

 

 


2. Web.xml & WebApplicationInitializer

package com.company.fia;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import com.company.fia.config.WebConfig;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;

public class FiaWebApplicationInitializer implements WebApplicationInitializer {

    private static final Logger log = LoggerFactory.getLogger(FiaWebApplicationInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        log.info("FiaWebApplicationInitializer.onStartup() call!!!!!!");

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(WebConfig.class); // 단일 클래스만 등록
        // context.scan("basePackages..."); // 패키지를 스캔 가능
        servletContext.addListener(new ContextLoaderListener(context));

        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }

}

WebApplicationInitializer가 기존의 web.xml의 역할을 대신 수행한다.

 


3. root-context.xml & @Configuration

package com.company.fia.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

    @Bean
    public SimpleDriverDataSource dataSource() {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class);
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/companyweb?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8");
        dataSource.setUsername("company");
        dataSource.setPassword("company");
        return dataSource;
    }
}

 


4. servlet-context.xml & WebMvcConfigurer

package com.company.fia.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.company.fia.interceptor.FiaInterceptor1;
import com.company.fia.interceptor.FiaInterceptor2;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.company.fia" })
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/styles/**").addResourceLocations("/WEB-INF/styles/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(new FiaInterceptor1()).addPathPatterns("/").excludePathPatterns("/css/**", "/js/**");
        registry.addInterceptor(new FiaInterceptor2()).addPathPatterns("/").excludePathPatterns("/css/**", "/js/**");
    }

}

 


5. Filter

package com.company.fia.filter;

import java.io.IOException;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;

@Component // 모든 http 메소드 처리.
@WebFilter(urlPatterns = "/") // 특정 url만 처리.
@Order(1) // Filter가 두개 이상이 될 경우 실행 순서 결정.
public class FiaFilter1 implements Filter {

    private static final Logger log = LoggerFactory.getLogger(FiaFilter1.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info((new Date()).toString() + " ==> Filter ::: FiaFilter1 Constructor");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info((new Date()).toString() + " ==> Filter111 ::: doFilter pre(1)");
        chain.doFilter(request, response);
        log.info((new Date()).toString() + " ==> Filter111 ::: doFilter after(1)");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
  • @WebFilter(urlPatterns = "/") : 자바 Servlet 필터에서 사용되는 어노테이션. 설정을 위한 별개의 파일이 필요하지 않는다.

 


6. Interceptor

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.company.fia"  })
public class WebConfig inplements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(new FiaInterceptor1()).addPathPatterns("/").excludePathPatterns("/css/**", "/js/**");
        registry.addInterceptor(new FiaInterceptor2()).addPathPatterns("/").excludePathPatterns("/css/**", "/js/**");
    }
}

Interceptor를 사용하기 위해서는 servlet-context.xml에 등록했었다.

 

이를 대신하는 WebMvcConfigurer 구현체(= WebConfig)의 addInterceptors()를 사용하면 된다.

 


7. AOP

package com.company.fia.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
    ...
}
  • @EnableAspectJAutoProxy : root-context.xml<aop:aspectj-autoproxy/> 대신.

 


'BE > Spring' 카테고리의 다른 글

[Spring] File Upload & Download  (0) 2024.07.06
[Spring] ControllerAdvice  (0) 2024.07.06
[Spring] AOP  (0) 2024.07.06
[Spring] Interceptor  (0) 2024.07.06
[Spring] Filter  (0) 2024.07.06