낭만 프로그래머

Spring Boot 기본 세팅 (DB + Mybatis + Log4j2) 본문

Java/Spring

Spring Boot 기본 세팅 (DB + Mybatis + Log4j2)

조영래 2020. 11. 4. 16:51

프로젝트 할 때마다 세팅하는것을 반복적으로 해서 이렇게 글을 올려 놓는다
Spring Tool Suite 4, Spring Boot v2.3.5, MS-SQL, Tomcat9 로 작업하였음.

itAssetManagement_workspace.z01
10.00MB
itAssetManagement_workspace.z02
10.00MB
itAssetManagement_workspace.z03
10.00MB
itAssetManagement_workspace.z04
10.00MB
itAssetManagement_workspace.z05
10.00MB
itAssetManagement_workspace.z06
10.00MB
itAssetManagement_workspace.z07
10.00MB
itAssetManagement_workspace.z08
10.00MB
itAssetManagement_workspace.z09
10.00MB
itAssetManagement_workspace.zip
3.06MB

 

<구조>



1. UserMapper.java

package com.ariulsoft.itassetmanagement.mapper;

import java.util.List;

import com.ariulsoft.itassetmanagement.model.User;

public interface UserMapper {
	List<User> getUsers() throws Exception;
} 

 

2. User.java

package com.ariulsoft.itassetmanagement.model;

public class User {
	private String labelCountry;
	private String country;
	
	public String getLabelCountry() {
		return labelCountry;
	}
	public void setLabelCountry(String labelCountry) {
		this.labelCountry = labelCountry;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
}

 

3. ApplicationService.java

package com.ariulsoft.itassetmanagement.service;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import com.ariulsoft.itassetmanagement.mapper.UserMapper;
import com.ariulsoft.itassetmanagement.model.User;

@Service
public class ApplicationService {
	private static final Logger LOGGER = LogManager.getLogger(ApplicationService.class);
	
	
	@Autowired
	private DataSourceTransactionManager transactionManager;
	
	@Autowired
	private UserMapper userMapper;
	
//	public void DBTest() {
//		TransactionStatus txStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
//		try {
//		  userMapper.insertUser(user);
//		}
//		catch (Exception e) {
//		  transactionManager.rollback(txStatus);
//		  throw e;
//		}
//		transactionManager.commit(txStatus);
//	}
	
	public List<User> getUserList() throws Exception {
		LOGGER.info("Hello Info level log");
		
		return userMapper.getUsers();
	}
}

 

4. ApplicationConfig.java

package com.ariulsoft.itassetmanagement;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ariulsoft.itassetmanagement.mapper.UserMapper;

@Configuration
public class ApplicationConfig {

//	@Autowired
//	SqlSessionFactory sqlSessionFactory;
	
	
//	@Bean({"dataSource"})
//    public DataSource getDataSource() {
//        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
//        dataSourceBuilder.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//        dataSourceBuilder.url("jdbc:sqlserver://192.168.0.44:1433;databaseName=LabelDesigner");
//        dataSourceBuilder.username("sa");
//        dataSourceBuilder.password("1234");
//        return dataSourceBuilder.build();
//    }
	
//	@Bean
//	public UserMapper userMapper() throws Exception {
//	  SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
//	  return sqlSessionTemplate.getMapper(UserMapper.class);
//	}
}

 

5. ItAssetManagement.java

package com.ariulsoft.itassetmanagement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class ItAssetManagementApplication {

	public static void main(String[] args) {
		SpringApplication.run(ItAssetManagementApplication.class, args);
	}

}

 

6. ServletInitializer.java

package com.ariulsoft.itassetmanagement;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(ItAssetManagementApplication.class);
	}

}

 

7. UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.ariulsoft.itassetmanagement.mapper.UserMapper">
    <select id="getUsers" resultType="com.ariulsoft.itassetmanagement.model.User">
        SELECT *
        FROM LabelCountry
    </select>
 
</mapper>

 

8. application.properties
    - 비어있음

9. applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	  <property name="dataSource" ref="dataSource" />
	  <property name="mapperLocations" value="classpath*:config/mappers/*.xml" />
	  <property name="transactionFactory">
	    <bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
	  </property>
	</bean>
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	  <constructor-arg ref="dataSource" />
	</bean>
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
	  <property name="mapperInterface" value="com.ariulsoft.itassetmanagement.mapper.UserMapper" />
	  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
        <property name="url" value="jdbc:sqlserver://192.168.0.44:1433;databaseName=LabelDesigner"></property>
        <property name="username" value="sa"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>

 

10. log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" monitorInterval="30">
    <Properties>
        <Property name="LOG_FORMAT">%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Property>
        <Property name="BASE_DIR">c:/log</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_FORMAT}"/>
        </Console>
        <RollingFile name="File"
                     fileName="${BASE_DIR}/ItAssetManagement.log"
                     filePattern="${BASE_DIR}/bootdemo.%d{yyyyMMdd}.log">
            <PatternLayout pattern="${LOG_FORMAT}"/>
            <Policies>
                <TimeBasedTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy>
                <Delete basePath="${BASE_DIR}">
                    <IfFileName glob="*.log" />
                    <IfLastModified age="30d" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File" />
        </Root>
    </Loggers>
</Configuration>

 

11. index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.springframework.web.context.support.SpringBeanAutowiringSupport"%>
<%@ page import="org.springframework.beans.factory.annotation.Autowired" %>
<%@ page import="com.ariulsoft.itassetmanagement.service.ApplicationService" %>
<%@ page import="com.ariulsoft.itassetmanagement.model.User" %>
<%@ page import="java.util.List"%>

<%!
	public void jspInit() { 
	    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, getServletContext()); //Autowired를 사용하기 위해
	}

	@Autowired
	private ApplicationService applicationService;
%>

<%
	java.util.List<User> userList = applicationService.getUserList();
	System.out.println(userList);
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

 

12. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.ariulsoft</groupId>
	<artifactId>ItAssetManagement</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>ItAssetManagement</name>
	<description>IT Asset Management</description>

	<properties>
		<java.version>11</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter</artifactId>
		    <exclusions>
		        <exclusion>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-logging</artifactId>
		        </exclusion>
		    </exclusions>
		</dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.6</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.3.3</version>
		</dependency>
		
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>4.3.18.RELEASE</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
		<dependency>
		    <groupId>com.microsoft.sqlserver</groupId>
		    <artifactId>mssql-jdbc</artifactId>
		    <version>7.4.1.jre11</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

13. server.xml
       - URIEncoding="UTF-8" 추가

0 Comments
댓글쓰기 폼