23.06.15
DEVOTEE를 활성화 시키면
지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.
버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.
| 컨텐츠 유형 | 제목 | 저장일 | 삭제 |
|---|
본인인증 로그인에 실패하였습니다.
회원이 아니시거나 본인인증 등록이
완료되지 않은 사용자입니다.
Springboot 가 아닌 Spring Framework 프로젝트들은 xml 기반으로 config 를 관리하는 경우가 많을 수 있습니다.
이번 글에서는 xml 기반으로 작성된 프로젝트를 java config 기반의 프로젝트로 마이그레이션 해보겠습니다.
project 소스 코드는 github 에 있고, commit 단위로 마이그레이션을 따라가보시는 것을 추천드립니다
https://github.com/HaJaeKwon/spring-migration-xml-to-java/commits/master
.png)
@Configuration 을 붙이는 하나의 클래스 단위와 유사applicationContext.xml 의 빈들을 등록하고, Servlet WebApplicationContext 에는 servlet-context.xml 의 빈들을 등록합니다.전환 순서
user.name=tango
String 타입의 userName 빈 객체가 등록되어있고, 값은 application.properties 파일의 user.name 값을 가져옵니다.
클래스로 만들기 위해 @Configuration 어노테이션을 사용한 Config 클래스를 추가하고, applicationContext.xml 에서 applicationContext-config.xml 파일을 import 하는 부분을 제거 합니다.
태그는 @ImportResource 어노테이션과 동일하고, 이는 자바 파일이 아니라 xml 파일을 import 할 때 사용합니다.
@Configuration
public class Config {
@Bean
public String userName(@Value("${user.name}") String userName) {
return userName;
}
}
...
테스트를 돌려보면 'hello tango' 프로퍼티 값이 정상적으로 반환됨을 확인할 수 있습니다.
.png)
classpath:application.properties
applicationContext.xml 의 PropertyPlaceholderConfigurer, component-scan 부분을 전환하기 위해 AppConfig 클래스를 생성했습니다.
빈 설정의 property 로 넘기는 값들은 해당 클래스의 메소드로 선언되어 있기에 setter 를 사용하여 똑같이 설정해주면 되고, applicationContext.xml 에서 전환한 부분들을 주석 처리합니다.
@Configuration
@ComponentScan("com.tango.migration")
@PropertySource("classpath:application.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
placeholderConfigurer.setFileEncoding("UTF-8");
placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
placeholderConfigurer.setIgnoreResourceNotFound(true);
return placeholderConfigurer;
}
}
그리고 테스트를 돌려보면...
.png)
우리가 설정한 user.name 의 값이, 예상한 tango 가 아니라 다른 값이 나오고 있습니다.
아마 다른 곳에서 설정된 값이 덮어씌워진 것으로 예상되는데, 지금은 user.name 이 아닌 name 을 키값으로 변경하고 전환을 진행하겠습니다.
보통은 이런 경우를 막기 위해 app.user.name 과 같이 prefix 를 붙여서, 해당 프로젝트에서 설정된 값임을 명시하는게 좋을 것 같습니다.
그리고 테스트를 돌려보면 성공함을 알 수 있습니다.
.png)
applicationContext.xml 의 마지막 설정인 cache 관련 설정을 전환해보겠습니다.
cache 관련 설정은 총 3가지입니다
@Configuration
@EnableCaching
@ComponentScan("com.tango.migration")
@PropertySource("classpath:application.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
placeholderConfigurer.setFileEncoding("UTF-8");
placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
placeholderConfigurer.setIgnoreResourceNotFound(true);
return placeholderConfigurer;
}
@Bean
public EhCacheCacheManager cacheManager(EhCacheManagerFactoryBean factoryBean) {
EhCacheCacheManager cacheManager = new EhCacheCacheManager();
cacheManager.setCacheManager(factoryBean.getObject());
return cacheManager;
}
@Bean
public EhCacheManagerFactoryBean ehcache(ApplicationContext context) {
EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
factoryBean.setConfigLocation(context.getResource("classpath:ehcache.xml"));
factoryBean.setShared(true);
return factoryBean;
}
}
applicationContext.xml 의 전환이 완료되었지만, 아직 web.xml 에서 해당 파일을 참조하고 있기에 삭제해서는 안됩니다.
Web MVC, Servlet 관련 설정 파일인 servlet-context.xml 을 전환하겠습니다.
앞서 수행해주셨던 것 처럼 @Configuration 클래스 파일을 생성하고, 내부에 태그 명과 일치하는 어노테이션을 사용하여 자바 코드로 선언해주시면 됩니다.
다만 Web MVC 설정들을 같이 가져와야 하기에 WebMvcConfigurer 의 구현체로 클래스를 작성해주셔야 합니다.
Spring Framework 4.3.16 에서 implements WebMvcConfigurer 를 하면 @EnableWebMvc 를 해주어도 인터페이스 내부 메소드들을 모두 구현해주라는 에러가 뜨게 됩니다.
WebMvcConfigurer 는 5.0 이후 부터 default 가 되었기에 이 부분에서는 Spring Framework 5.0.0.RELEASE 버전 업 후에 진행하겠습니다.
5.0 이전에서는 WebMvcConfigureAdapter 를 참고 부탁드립니다.
WebMvcConfigurationSupport 의 설정 값들을 가져온다
@Configuration
@EnableWebMvc
@ComponentScan("com.tango.migration")
public class WebMvcConfig implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogIntercepter())
.addPathPatterns("/**")
.excludePathPatterns("/");
}
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {WebMvcConfig.class, AppConfig.class})
@WebAppConfiguration
public class HelloControllerTest {
...
}
.png)
appServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:servlet-context.xml
1
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
appServlet
/
이제 마지막으로 web.xml 설정을 대신할 WebApplicationInitializer 인터페이스의 구현체인 WebInit class 를 만들고 전환해보도록 하겠습니다.
Web MVC 설정들은 태그로 DispatcherServlet 을 선언하고, 이름은 appServlet, 설정은 servlet-context.xml 을 사용하라고 지시하고 있습니다.
Web MVC 관련된 설정이 아닌 것들은 태그로 applicationContext.xml 을 사용하라고 지시하고 있습니다.
위 두가지를 java code 로 변환하게 되면 AnnotationConfigWebApplicationContext 객체로 만들어 container 에 등록하게 됩니다.
encodingFilter 객체를 만들어서 /* 경로에 맵핑하고, appServlet 이라는 servlet 을 / 경로에 맵핑해주면 전환이 완료됩니다.
public class WebInit implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
container.addListener(new ContextLoaderListener(appContext));
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
container.addFilter("encodingFilter", encodingFilter)
.addMappingForUrlPatterns(null, false, "/*");
AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
servletContext.register(WebMvcConfig.class);
ServletRegistration.Dynamic appServlet = container.addServlet("appServlet", new DispatcherServlet(servletContext));
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
}
}
@ContextConfiguration 에서 WebMvcConfig.class 대신 WebInit.class 설정을 불러오도록 코드 수정을 한 후 테스트 해보겠습니다.
.png)
Spring boot 의 @SpringBootApplication 어노테이션이 정말 많은 일들을 해주어서 Spring 이라는 프레임워크가 WAS 위에서 어떻게 구동되는건지 잘 몰랐습니다.
이번 기회를 통해 각각의 Context 가 어떤 설정 파일을 필요로 하고, 그것들이 어떻게, 어느 시점에 연결되는지 알게 되었습니다.
DEVOTEE를 활성화 시키면
지금 작성한 댓글에 AI가 댓글을 달아줍니다.