ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring MVC 기본 설정 02 - Annotation을 이용한 Spring mvc Config
    Java/Spring 2018. 12. 19. 14:35

    Spring mvc 프로젝트를 구성할때 제일 많이 사용하는 설정 방식은 xml을 이용한 방식이다.


    xml을 이용하는 방식은 널리 퍼져있어서 검색하기에는 좋지만 내가 보기엔 가독성이 떨어지고 이해하기가 힘든 구석이 있어보인다.


    java annotation을 이용해 spring mvc 를 설정하는 방식을 공부하고 적용해가면서 기록을 남기려고 한다.


    기본적인 dependency는 이전글(클릭) 에서 추가했다는 가정하에 진행하고자 한다.


    모든 config 관련 class들은 {기본 패키기}.config 라는 패키지에 생성하도록 한다.


    1. WebMvcConfig 설정


    WebMvcConfig 클래스는 기본적인 서블릿 설정을 하는 클래스라고 생각하면 된다.


    ViewResolver 설정을 여기서 할 수있다.


    @Configuration annotation으로 이 클래스는 config 클래스라고 명시를 해준다.

    @EnableWebMvc annotation으로 Spring Web Mvc 설정 클래스라고 명시를 해준다.

    @ComponentScan으로 후에 @Autowired 로 자동으로 DI가 될 수 있는 component들의 기본 경로를 설정한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    package com.pang.pangs_spring_mvc.config;
     
    import org.springframework.context.annotation.Bean;
    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.WebMvcConfigurer;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;
     
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = { "com.pang.springdemo" })
    public class WebMvcConfig implements WebMvcConfigurer {
     
        // View resolver 설정
        @Bean
           public InternalResourceViewResolver resolver() {
              InternalResourceViewResolver resolver = new InternalResourceViewResolver();
              resolver.setViewClass(JstlView.class);
              resolver.setPrefix("/WEB-INF/views/");
              resolver.setSuffix(".jsp");
              return resolver;
           }
    }
     
    cs



    2. HibernateConfig 설정




    2.1. application.properties에 database 접속 정보 및 hibernate 설정 값 입력


    Spring orm 매핑으로 hibernate를 사용할 거니 hibernate 설정 파일을 작성한다.


    src/main/resources 폴더를 생성하고 application.properties 라는 파일을 생성한다.


    application.properties 파일에는 프로젝트 설정 값들을 입력해놓고 입력한 설정 정보를 설정 클래스에서 접근해서 사용한다.


    이렇게 설정 정보를 파일로 빼놓는 이유는 소스를 공개할때 민감한 정보는 공개하지 않기 위한 이유도 있고


    만약설정 정보가 바뀌었을때 손 쉽게 설정값만 변경하면 되니 유지보수적인 측면에서도 이유가 된다.



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    #
    # JDBC connection properties
    #
    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://{mysql url}/{schema_name}?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
    jdbc.user={userName}
    jdbc.password={password}
     
    #
    # Connection pool properties
    #
    connection.pool.initialPoolSize=5
    connection.pool.minPoolSize=5
    connection.pool.maxPoolSize=20
    connection.pool.maxIdleTime=3000
     
    #
    # Hibernate properties
    #
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.show_sql=true
    hibernate.packagesToScan={기본패키지}.entity
    cs



    2.2 HibernateConfig class 설정


    2.1 단계에서 입력한 디비 정보를 입력하는 config class를 생성한다.


    클래스 명을 HibernateConfig 로 생성했다.


    Connection pool 을 생성하고 hibernate 설정과 sessionfactory 설정 transaction 설정을 했다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    package com.pang.pangs_spring_mvc.config;
     
    import java.beans.PropertyVetoException;
    import java.util.Properties;
    import java.util.logging.Logger;
     
    import javax.sql.DataSource;
     
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.ComponentScans;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.core.env.Environment;
    import org.springframework.orm.hibernate5.HibernateTransactionManager;
    import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
     
    import com.mchange.v2.c3p0.ComboPooledDataSource;
     
    @Configuration
    @EnableTransactionManagement
    @ComponentScans(value = { @ComponentScan("com.pang.pangs_spring_mvc")})
    @PropertySource({ "classpath:application.properties" })
    public class HibernateConfig {
        
        @Autowired
        private Environment env;
     
        private Logger logger = Logger.getLogger(getClass().getName());
        
        @Bean
        public DataSource myDataSource() {
            
            // Connection Pool을 생성한다.
            ComboPooledDataSource myDataSource = new ComboPooledDataSource();
     
            // jdbc driver 설정을 한다.
            try {
                myDataSource.setDriverClass("com.mysql.jdbc.Driver");        
            }
            catch (PropertyVetoException exc) {
                throw new RuntimeException(exc);
            }
            
            // 연결정보가 옳바른지 로그를 남긴다.
            logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
            logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
            
            // database connection props 설정.
            myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
            myDataSource.setUser(env.getProperty("jdbc.user"));
            myDataSource.setPassword(env.getProperty("jdbc.password"));
            
            // connection pool props 설정.
            myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
            myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
            myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));        
            myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
     
            return myDataSource;
        }
        
        private Properties getHibernateProperties() {
     
            // hibernate properties 설
            Properties props = new Properties();
     
            props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
            props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
            
            return props;                
        }
        
        // need a helper method 
        // read environment property and convert to int
        
        private int getIntProperty(String propName) {
            
            String propVal = env.getProperty(propName);
            
            // now convert to int
            int intPropVal = Integer.parseInt(propVal);
            
            return intPropVal;
        }    
        
        @Bean
        public LocalSessionFactoryBean sessionFactory(){
            
            // create session factory bean
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            
            // set the properties
            sessionFactory.setDataSource(myDataSource());
            sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
            sessionFactory.setHibernateProperties(getHibernateProperties());
            
            return sessionFactory;
        }
        
        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
            
            // setup transaction manager based on session factory
            HibernateTransactionManager txManager = new HibernateTransactionManager();
            txManager.setSessionFactory(sessionFactory);
     
            return txManager;
        }
        
        
    }
     
    cs



    3. AppInitializer 클래스 설정


    위의 단계에서 설정한 config 클래스를 합치는 작업을 해야한다. 


    이름도 매우긴 AbstractAnnotationConfigDispatcherServletInitializer 클래스를 상속받아 마지막 설정 클래스를 완성한다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package com.pang.pangs_spring_mvc.config;
     
    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
     
    public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
     
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { HibernateConfig.class };
        }
     
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[] { WebMvcConfig.class };
        }
     
        @Override
        protected String[] getServletMappings() {
            return new String[] {"/"};
        }
    }
     
    cs





    4. 설정 완료 및 테스트


    Spring MVC 설정을 완료했다. 


    HomeController 와 index.jsp 를 만들어서 프로젝트가 정상적으로 돌아가는지 확인 해보자. 


    설정이 하나라도 잘못 됐다면 빌드하는 도중에 에러가 나올 것이다.


    404가 발생한다면 component scan 에서 옳바른 패키지 명을 입력했는지 확인해보고 그래도 안될경우


    tomcat의 context 를 확인해봐야한다. 


    500 에러가 발생한다면 db 정보를 확인해 봐야 알 수 있을 것이다. 




    5. Github 주소


    git 주소를 첨부하니 자세한 소스는 clone 으로 받아서 확인해보면 좋을듯 하다.


    https://github.com/euihyunHwang/spring-mvc-starter.git



    댓글

Designed by Tistory.