안녕하세요. J4J입니다.
이번 포스팅은 설정 파일을 변경하는 다양한 방법에 대해 적어보는 시간을 가져보려고 합니다.
최근 스프링 설정 파일의 추세는 익숙하지 않은 xml파일보다 익숙한 환경의 Java파일로 설정하는 추세라고 개인적으로 생각합니다.
그리고 변경하는 방법에는 다양한 방법들이 있는데 그중 제가 알고 있는 방법들을 정리해보고자 합니다.
root-context와 service-context 모두 각각 2가지 방법밖에 모르지만요 ㅎㅎ..
제 블로그에서 사용했던 JPA와 MyBatis 설정방법까지 같이 포함하여 변경해보도록 하겠습니다.
변경 전 root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.11.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- jpaRepository scan -->
<jpa:repositories base-package="com.spring.javaConfig.repository" />
<!-- mapper scan -->
<mybatis-spring:scan base-package="com.spring.javaConfig.repository"/>
<!-- component scan -->
<context:component-scan base-package="com.spring.javaConfig.service" />
<!-- db 설정 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- jpa 설정 -->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="jpa-mysql" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<!-- mybatis 설정 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- transactional 설정 -->
<bean id="myBatisTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.data.transaction.ChainedTransactionManager">
<constructor-arg>
<list>
<ref bean="jpaTransactionManager"/>
<ref bean="myBatisTransactionManager"/>
</list>
</constructor-arg>
</bean>
<!-- @EnableTransactionManagement -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
혹시 태그를 사용하는데 에러가 발생하시는 분은 xml파일 하단의 Namespaces탭을 다음과 같이 변경해주시면 됩니다.
root-context 변경 방법 1
[ 1. web.xml에서 context-parm의 configLocation 수정 ]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 자바설정으로 변경 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.javaConfig.config.RootContext</param-value>
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
...
</web-app>
[ 2. RootContext 클래스 ]
package com.spring.javaConfig.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = {"com.spring.javaConfig.repository"})
@MapperScan(basePackages = {"com.spring.javaConfig.repository"})
@ComponentScan(basePackages = {"com.spring.javaConfig.service"})
@EnableTransactionManagement
public class RootContext {
// db 설정
@Bean
public BasicDataSource dataSource() {
BasicDataSource datasource = new BasicDataSource();
datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");
datasource.setUrl("jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC");
datasource.setUsername("root");
datasource.setPassword("root");
return datasource;
}
// jpa 설정
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setPersistenceUnitName("jpa-mysql");
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return entityManagerFactory;
}
// mybatis 설정
@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource());
sqlSessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
return sqlSessionFactory;
}
@Bean
public SqlSessionTemplate sqlSession(SqlSessionFactoryBean sqlsessionFactory) throws Exception {
return new SqlSessionTemplate(sqlsessionFactory.getObject());
}
// transactional 설정
@Bean
public PlatformTransactionManager transactionManager() throws Exception {
DataSourceTransactionManager myBatisTransactionManager = new DataSourceTransactionManager();
myBatisTransactionManager.setDataSource(dataSource());
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
ChainedTransactionManager transactionManager = new ChainedTransactionManager(jpaTransactionManager, myBatisTransactionManager);
return transactionManager;
}
}
root-context 변경 방법 2
[ 0. web.xml 기존 설정 유지 ]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 기존 설정 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
...
</web-app>
[ 1. root-context.xml 설정 변경 ]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.11.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 자바설정으로 변경 -->
<bean class="com.spring.javaConfig.config.RootContext"></bean>
</beans>
[ 2. RootConetxt 클래스 ] - 변경 방법 1과 동일
package com.spring.javaConfig.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = {"com.spring.javaConfig.repository"})
@MapperScan(basePackages = {"com.spring.javaConfig.repository"})
@ComponentScan(basePackages = {"com.spring.javaConfig.service"})
@EnableTransactionManagement
public class RootContext {
// db 설정
@Bean
public BasicDataSource dataSource() {
BasicDataSource datasource = new BasicDataSource();
datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");
datasource.setUrl("jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC");
datasource.setUsername("root");
datasource.setPassword("root");
return datasource;
}
// jpa 설정
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setPersistenceUnitName("jpa-mysql");
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return entityManagerFactory;
}
// mybatis 설정
@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource());
sqlSessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
return sqlSessionFactory;
}
@Bean
public SqlSessionTemplate sqlSession(SqlSessionFactoryBean sqlsessionFactory) throws Exception {
return new SqlSessionTemplate(sqlsessionFactory.getObject());
}
// transactional 설정
@Bean
public PlatformTransactionManager transactionManager() throws Exception {
DataSourceTransactionManager myBatisTransactionManager = new DataSourceTransactionManager();
myBatisTransactionManager.setDataSource(dataSource());
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
ChainedTransactionManager transactionManager = new ChainedTransactionManager(jpaTransactionManager, myBatisTransactionManager);
return transactionManager;
}
}
변경 전 servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- component scan -->
<context:component-scan base-package="com.spring.javaConfig.controller" />
<!-- EnableWebMVC -->
<annotation-driven />
<!-- resource 등록 -->
<resources mapping="/resources/**" location="/resources/" />
<!-- viewResolver 설정 -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
servlet-context 변경 방법 1
[ 1. web.xml에서 servlet설정의 init-param 수정 ]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
...
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 자바설정으로 변경 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.javaConfig.config.ServletContext</param-value>
</init-param>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
...
</servlet>
...
</web-app>
[ 2. ServletContext 클래스 ]
package com.spring.javaConfig.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.spring.javaConfig.controller"})
public class ServletContext implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { // resource 등록
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public ViewResolver viewResolver() { // viewResolver 설정
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/views/");
vr.setSuffix(".jsp");
return vr;
}
}
servlet-context 변경 방법 2
[ 0. web.xml 기존 설정 유지 ]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
...
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 기존 설정 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
...
</servlet>
...
</web-app>
[ 1. servlet-context 설정 변경 ]
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 자바설정으로 변경 -->
<context:annotation-config />
<beans:bean class="com.spring.javaConfig.config.ServletContext" />
</beans:beans>
[ 2. ServletContext 클래스 ] - 1번 방법과 달리 config도 componentScan에 추가
package com.spring.javaConfig.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.spring.javaConfig.controller", "com.spring.javaConfig.config"}) // config 추가
public class ServletContext implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { // resource 등록
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public ViewResolver viewResolver() { // viewResolver 설정
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/views/");
vr.setSuffix(".jsp");
return vr;
}
}
이상으로 설정 파일을 변경하는 다양한 방법에 대해 간단하게 알아보는 시간이었습니다.
읽어주셔서 감사합니다.
'Spring > Spring' 카테고리의 다른 글
[Spring] Filter를 이용하여 Request Parameter 조작하기 (0) | 2021.11.11 |
---|---|
[Spring] 파일 다운로드 (1) | 2021.06.07 |
[Spring] JWT 구현하기 (2) (2) | 2021.04.09 |
[Spring] JWT 구현하기 (1) (0) | 2021.04.08 |
[Spring] JWT란? (0) | 2021.04.07 |
댓글