페이지

2021년 9월 16일 목요일

Spring + MyBatis + Oracle 사용 기초

Spring + MyBatis + Oracle 사용 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Maven 3.8.2
  • Spring Boot 2.5.4
  • Oracle DB 19
  • MyBatis 2.2.0

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    브라우져에서 spring initializr를 방문하여 아래와 같이 입력하고 GENERATE 버튼을 클릭합니다.

    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.4
    • Project Meta:
      • Group: trvoid.mybatis
      • Artifact: basic-mybatis-example
      • Name: basic-mybatis-example
      • Package name: trvoid.mybatis
      • Packaging: Jar
      • Java: 8
    • Dependencies:
      • JDBC API
      • MyBatis Framework
      • Oracle Driver

    생성된 프로젝트 파일을 다운로드하여 압축을 풉니다. 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-src
        |-main
          |-java
            |-trvoid.mybatis
              |-BasicMybatisExampleApplication.java
          |-resources
            |-application.properties
        |-test
          |-java
            |-trvoid.mybatis
              |-BasicMybatisExampleApplicationTests.java
      |-pom.xml
    

    pom.xml 파일에서 의존성 항목과 빌드 플러그인을 확인할 수 있습니다.

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>  
           <groupId>org.mybatis.spring.boot</groupId>  
           <artifactId>mybatis-spring-boot-starter</artifactId>  
           <version>2.2.0</version>  
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>
        </plugins>
    </build>
    

    BasicMybtisExampleApplication.java 파일의 내용은 아래와 같습니다.

    package trvoid.mybatis;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class BasicMybatisExampleApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(BasicMybatisExampleApplication.class, args);
        }
    
    }
    
  2. @Mapper 추가

    src/main/java/trvoid/mybatis/Car.java

    package trvoid.mybatis;
    
    public class Car {
        private int id;
        private String model;
        private String manufacturer;
    
        public Car(int id, String model, String manufacturer) {
            this.id = id;
            this.model = model;
            this.manufacturer = manufacturer;
        }
    
        // getters and setters
    
        @Override
        public String toString() {
            return String.format("id:%d, model:%s, manufacturer:%s", id, model, manufacturer);
        }
    }
    

    src/main/java/trvoid/mybatis/CarMapper.java

    package trvoid.mybatis;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    @Mapper
    public interface CarMapper {
        String SELECT = " SELECT ID, MODEL, MANUFACTURER FROM CAR ";
    
        @Select(" SELECT COUNT(1) FROM ALL_OBJECTS " +
                " WHERE OBJECT_TYPE = 'TABLE' AND OBJECT_NAME = 'CAR' ")
        int countTable();
    
        @Insert(" CREATE TABLE CAR ( " +
                "    ID NUMBER(10) NOT NULL, " +
                "    MODEL VARCHAR2(100) NOT NULL, " +
                "    MANUFACTURER VARCHAR2(100) NULL, " +
                "    CONSTRAINT CAR_PK PRIMARY KEY (ID) " +
                " ) ")
        void createTable();
    
        @Insert(" INSERT INTO CAR ( " +
                "    ID, MODEL, MANUFACTURER " +
                " ) VALUES ( " +
                "    #{car.id}, #{car.model}, #{car.manufacturer,jdbcType=VARCHAR} " +
                " ) ")
        void insertCar(@Param("car") Car car);
    
        @Select(SELECT + " WHERE ID = #{carId} ")
        Car getCar(@Param("carId") String carId);
    
        @Select(SELECT)
        List<Car> findAll();
    }
    
  3. 데이터베이스 질의 수행을 위해 CommandLineRunner 추가

    CAR 테이블이 없을 경우 생성하고 세 개의 행을 추가합니다.

    src/main/java/trvoid/mybatis/BasicMybatisExampleApplication.java

    package trvoid.mybatis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import javax.sql.DataSource;
    import java.util.List;
    
    @SpringBootApplication
    public class BasicMybatisExampleApplication implements CommandLineRunner {
        @Autowired
        DataSource dataSource;
    
        @Autowired
        CarMapper carMapper;
    
        public static void main(String[] args) {
            SpringApplication.run(BasicMybatisExampleApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("DataSource = " + dataSource);
    
            if (carMapper.countTable() == 0) {
                carMapper.createTable();
                System.out.println("** Created a table: CAR");
    
                int carId = ((int)Math.random()) % 100;
    
                Car car1 = new Car(carId + 0, "J1", "Jelly");
                carMapper.insertCar((car1));
                System.out.println(String.format("** Inserted a car: %s", car1.toString()));
    
                Car car2 = new Car(carId + 1, "T1", "Teal");
                carMapper.insertCar((car2));
                System.out.println(String.format("** Inserted a car: %s", car2.toString()));
    
                Car car3 = new Car(carId + 2, "W1", "Wisdom");
                carMapper.insertCar((car3));
                System.out.println(String.format("** Inserted a car: %s", car3.toString()));
            }
    
            System.out.println("== CARS ==");
            List<Car> list = carMapper.findAll();
            list.forEach(x -> System.out.println(x));
            System.out.println("-- CARS --");
    
            System.exit(0);
        }
    }
    
  4. 데이터 소스 설정

    src/main/resources/application.properties

    spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
    spring.datasource.username=your_db_username
    spring.datasource.password=your_db_password
    spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
    
  5. 컴파일

    >mvn compile
    
  6. 실행

    >mvn spring-boot:run
    

    출력 결과

    ...
    DataSource = HikariDataSource (HikariPool-1)
    == CARS ==
    id:1, model:J1, manufacturer:JELLY
    id:2, model:T1, manufacturer:TEAL
    id:3, model:W1, manufacturer:WISDOM
    -- CARS --
    ...
    

Written with StackEdit.

2021년 9월 10일 금요일

Spring + JdbcTemplate + Oracle 사용 기초

Spring + JdbcTemplate + Oracle 사용 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Maven 3.8.2
  • Spring Boot 2.5.4
  • Oracle DB 19

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    브라우져에서 spring initializr를 방문하여 아래와 같이 입력하고 GENERATE 버튼을 클릭합니다.

    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.4
    • Project Meta:
      • Group: trvoid.jdbc
      • Artifact: basic-jdbc-example
      • Name: basic-jdbc-example
      • Package name: trvoid.jdbc
      • Packaging: Jar
      • Java: 8
    • Dependencies: JDBC API, Oracle Driver

    생성된 프로젝트 파일을 다운로드하여 압축을 풉니다. 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-src
        |-main
          |-java
            |-trvoid.jdbc
              |-BasicJdbcExampleApplication.java
          |-resources
            |-application.properties
        |-test
          |-java
            |-trvoid.jdbc
              |-BasicJdcExampleApplicationTests.java
      |-pom.xml
    

    pom.xml 파일에서 의존성 항목과 빌드 플러그인을 확인할 수 있습니다.

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>
        </plugins>
    </build>
    

    BasicJdbcExampleApplication.java 파일의 내용은 아래와 같습니다.

    package trvoid.jdbc;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class BasicJdbcExampleApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(BasicJdbcExampleApplication.class, args);
        }
    
    }
    
  2. JdbcTemplate을 사용하는 @Repository 추가

    src/main/java/trvoid/jdbc/Car.java

    package trvoid.jdbc;
    
    public class Car {
        private int id;
        private String model;
        private String manufacturer;
    
        public Car(int id, String model, String manufacturer) {
            this.id = id;
            this.model = model;
            this.manufacturer = manufacturer;
        }
    
        // getters and setters
    
        @Override
        public String toString() {
            return String.format("id:%d, model:%s, manufacturer:%s", id, model, manufacturer);
        }
    }
    

    src/main/java/trvoid/jdbc/CarRepository.java

    package trvoid.jdbc;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Repository
    public class CarRepository {
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        public List<Car> findAll() {
            List<Car> result = jdbcTemplate.query(
                    "SELECT id, model, manufacturer FROM car",
                    (rs, rowNum) -> new Car(
                            rs.getInt("id"),
                            rs.getString("model"),
                            rs.getString("manufacturer")
                    )
            );
    
            return result;
        }
    }
    
  3. 데이터베이스 질의 수행을 위해 CommandLineRunner 추가

    src/main/java/trvoid/jdbc/BasicJdbcExampleApplication.java

    package trvoid.jdbc;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import javax.sql.DataSource;
    import java.util.List;
    
    @SpringBootApplication
    public class BasicJdbcExampleApplication implements CommandLineRunner {
        @Autowired
        DataSource dataSource;
    
        @Autowired
        CarRepository carRepository;
        public static void main(String[] args) {
            SpringApplication.run(BasicJdbcExampleApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("DataSource = " + dataSource);
    
            System.out.println("== CARS ==");
            List<Car> list = carRepository.findAll();
            list.forEach(x -> System.out.println(x));
            System.out.println("-- CARS --");
    
            System.exit(0);
        }
    }
    
  4. 데이터 소스 설정

    src/main/resources/application.properties

    spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
    spring.datasource.username=your_db_username
    spring.datasource.password=your_db_password
    spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
    
  5. 테이블 생성 및 데이터 입력 SQL 작성

    src/main/resources/schema.sql

    CREATE TABLE CAR (
        ID NUMBER(10) NOT NULL,
        MODEL VARCHAR2(100) NOT NULL,
        MANUFACTURER VARCHAR2(100) NOT NULL,
        CONSTRAINT CAR_PK PRIMARY KEY (ID)
    );
    

    src/main/resources/data.sql

    INSERT INTO "CAR" (ID, MODEL, MANUFACTURER) VALUES(1, 'J5','JELLY');  
    INSERT INTO "CAR" (ID, MODEL, MANUFACTURER) VALUES(2, 'W7','WISDOM');  
    INSERT INTO "CAR" (ID, MODEL, MANUFACTURER) VALUES(3, 'T9','TEAL');
    
  6. Oracle 데이터베이스에서 테이블 생성 및 데이터 입력

    >sqlplus
    SQL> start src\main\resources\schema.sql
    SQL> start src\main\resources\data.sql
    SQL> commit;
    
  7. 컴파일

    >mvn compile
    
  8. 실행

    >mvn spring-boot:run
    

    출력 결과

    ...
    DataSource = HikariDataSource (HikariPool-1)
    == CARS ==
    id:1, model:J5, manufacturer:JELLY
    id:2, model:W7, manufacturer:WISDOM
    id:3, model:T9, manufacturer:TEAL
    -- CARS --
    ...
    

Written with StackEdit.

2021년 9월 7일 화요일

Maven + Spring 파일 업로드 기초

Maven + Spring 파일 업로드 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Maven 3.8.2
  • Spring 5.0.6

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    브라우져에서 spring initializr를 방문하여 아래와 같이 입력하고 GENERATE 버튼을 클릭합니다.

    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.4
    • Project Meta:
      • Group: trvoid
      • Artifact: file-upload
      • Name: File Upload
      • Package name: trvoid.fileupload
      • Packaging: Jar
      • Java: 8
    • Dependencies: Spring Web

    생성된 프로젝트 파일을 다운로드하여 압축을 풉니다. 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-src
        |-main
          |-java
            |-trvoid.fileupload
              |-FileUploadApplication.java
        |-test
          |-java
            |-trvoid.fileupload
              |-FileUploadApplicationTests.java
      |-pom.xml
    

    pom.xml 파일에서 의존성 항목과 빌드 플러그인을 확인할 수 있습니다.

    <dependencies>
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>
        </plugins>
    </build>
    

    FileUploadApplication.java 파일의 내용은 아래와 같습니다.

    package trvoid.fileupload;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class FileUploadApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FileUploadApplication.class, args);
        }
    
    }
    
  2. 파일 저장소 서비스 추가

    src/trvoid/fileupload/storage/StorageService.java

    package trvoid.fileupload.storage;
    
    import org.springframework.web.multipart.MultipartFile;
    
    public interface StorageService {
        void init();
        public void deleteAll()
        void store(MultipartFile file);
    }
    

    src/trvoid/fileupload/storage/FileSystemStorageService.java

    package trvoid.fileupload.storage;
    
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    @Service
    public class FileSystemStorageService implements StorageService {
        private final Path rootLocation;
    
        public FileSystemStorageService() {
            this.rootLocation = Paths.get("upload-dir");
        }
    
        @Override
        public void init() {
            try {
                Files.createDirectory(rootLocation);
            } catch (IOException e) {
                throw new RuntimeException("Could not initialize storage", e);
            }
        }
    	
    	@Override  
        public void deleteAll() {  
            FileSystemUtils.deleteRecursively(rootLocation.toFile());  
        }
    
        @Override
        public void store(MultipartFile file) {
            try {
                if (file.isEmpty()) {
                    throw new RuntimeException("Failed to store empty file " + file.getOriginalFilename());
                }
                Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
            } catch (IOException e) {
                throw new RuntimeException("Failed to store file " + file.getOriginalFilename(), e);
            }
        }
    }
    
  3. 컨트롤러 추가

    src/trvoid/fileupload/FileUploadController.java

    package trvoid.fileupload;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import trvoid.fileupload.storage.StorageService;
    
    @RestController
    public class FileUploadController {
        private final StorageService storageService;
    
        @Autowired
        public FileUploadController(StorageService storageService) {
            this.storageService = storageService;
        }
    
        @PostMapping("/file/upload")
        public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                       @RequestParam("fileUsage") String fileUsage) {
            storageService.store(file);
            
            System.out.println(String.format("File Usage: %s", fileUsage));
    
            return "success";
        }
    }
    
  4. 업로드 파일 크기와 요청 크기 제한

    src/main/resources/application.properties

    spring.servlet.multipart.max-file-size=128KB  
    spring.servlet.multipart.max-request-size=128KB
    
  5. 파일 저장소 초기화를 위해 CommandLineRunner 추가

    src/trvoid/fileupload/FileUploadApplication.java

    package trvoid.fileupload;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import trvoid.fileupload.storage.StorageService;
    
    @SpringBootApplication
    public class FileUploadApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FileUploadApplication.class, args);
        }
    
        @Bean
        CommandLineRunner init(StorageService storageService) {
            return (args) -> {
                storageService.deleteAll();
                storageService.init();
            };
        }
    }
    
  6. 컴파일

    >mvn compile
    
  7. 실행

    >mvn spring-boot:run
    
  8. 파일 업로드 요청

    HTTP 클라이언트 프로그램(Insomnia, Postman, cURL 등)에서 아래와 같이 지정하여 파일 업로드 요청

    요청이 정상적으로 처리되었다면 아래와 같은 응답이 표시될 것입니다.

    success
    

    현재 폴더 아래에 upload-dir이 생성되었고 그 아래에서 업로드 파일이 존재하는지 확인합니다. 그리고 서버 실행 터미널에 File Usage: xxx와 같은 문자열이 표시되는지 확인합니다.

Written with StackEdit.

Maven + Spring @RestController 사용 기초

Maven + Spring @RestController 사용 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Maven 3.8.2
  • Spring 5.0.6

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    브라우져에서 spring initializr를 방문하여 아래와 같이 입력하고 GENERATE 버튼을 클릭합니다.

    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.4
    • Project Meta:
      • Group: trvoid
      • Artifact: rest
      • Name: rest
      • Package name: trvoid
      • Packaging: Jar
      • Java: 8
    • Dependencies: Spring Web

    생성된 프로젝트 파일을 다운로드하여 압축을 풉니다. 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-src
        |-main
          |-java
            |-trvoid
              |-RestApplication.java
        |-test
          |-java
            |-trvoid
              |-RestApplicationTests.java
      |-pom.xml
    

    pom.xml 파일에서 의존성 항목과 빌드 플러그인을 확인할 수 있습니다.

    <dependencies>
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>
        </plugins>
    </build>
    

    RestApplication.java 파일의 내용은 아래와 같습니다.

    package trvoid;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class RestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(RestApplication.class, args);
        }
    
    }
    
  2. 컨트롤러 추가

    src/main/java/trvoid/Greeting.java

    package trvoid;
    
    public class Greeting {
        private String to;
        private String message;
    
        public Greeting(String to, String message) {
            this.to = to;
            this.message = message;
        }
    
        // getters and setters
    }
    

    src/main/java/trvoid/HelloController.java

    package trvoid;  
    
    import org.springframework.web.bind.annotation.GetMapping;  
    import org.springframework.web.bind.annotation.PathVariable;  
    import org.springframework.web.bind.annotation.RestController;  
    
    @RestController  
    public class HelloController {  
        @GetMapping(value="/{name}")  
        public Greeting sayHello(@PathVariable String name) {  
            return new Greeting("Server", name, "Hello");  
        } 
    }
    
  3. 컴파일

    >mvn compile
    
  4. 실행

    >mvn exec:java -Dexec.mainClass=trvoid.RestApplication
    

    실행 결과

    ...
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::                (v2.5.4)
    
    2021-09-08 10:45:34.564  INFO 39908 --- [lication.main()] trvoid.RestApplication                   : Starting RestApplication using Java 1.8.0_261 on DESKTOP-NBBJSSF with PID 39908 (D:\DevTest\Spring\rest-maven\target\classes started by WISECAN in D:\DevTest\Spring\rest-maven)
    2021-09-08 10:45:34.564  INFO 39908 --- [lication.main()] trvoid.RestApplication                   : No active profile set, falling back to default profiles: default
    2021-09-08 10:45:35.142  INFO 39908 --- [lication.main()] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2021-09-08 10:45:35.157  INFO 39908 --- [lication.main()] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2021-09-08 10:45:35.157  INFO 39908 --- [lication.main()] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.52]
    2021-09-08 10:45:35.204  INFO 39908 --- [lication.main()] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2021-09-08 10:45:35.204  INFO 39908 --- [lication.main()] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 617 ms
    2021-09-08 10:45:35.563  INFO 39908 --- [lication.main()] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2021-09-08 10:45:35.614  INFO 39908 --- [lication.main()] trvoid.RestApplication                   : Started RestApplication in 1.292 seconds (JVM running for 16.457)
    
  5. 브라우져로 REST API 호출 결과 확인

    브라우져에서 주소창에 http://localhost:8080/홍길동을 입력하고 엔터를 치면 아래와 같은 결과를 얻습니다.

    {"to":"홍길동","message":"Hello from Server"}
    

Written with StackEdit.

2021년 9월 6일 월요일

Gradle + Spring 사용 기초

Gradle + Spring 사용 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Gradle 7.2
  • Spring 5.0.6

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    >gradle init
    

    선택 항목

    Starting a Gradle Daemon (subsequent builds will be faster)
    
    Select type of project to generate:
      1: basic
      2: application
      3: library
      4: Gradle plugin
    Enter selection (default: basic) [1..4] 2
    
    Select implementation language:
      1: C++
      2: Groovy
      3: Java
      4: Kotlin
      5: Scala
      6: Swift
    Enter selection (default: Java) [1..6] 3
    
    Split functionality across multiple subprojects?:
      1: no - only one application project
      2: yes - application and library projects
    Enter selection (default: no - only one application project) [1..2] 1
    
    Select build script DSL:
      1: Groovy
      2: Kotlin
    Enter selection (default: Groovy) [1..2] 1
    
    Select test framework:
      1: JUnit 4
      2: TestNG
      3: Spock
      4: JUnit Jupiter
    Enter selection (default: JUnit Jupiter) [1..4] 1
    
    Project name (default: hello-gradle): hello
    Source package (default: hello): trvoid
    
    > Task :init
    Get more help with your project: https://docs.gradle.org/7.2/samples/sample_building_java_applications.html
    

    생성된 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-app
        |-src
          |-main
            |-java
              |-trvoid
                |-App.java
            |-resources
          |-test
            |-java
              |-trvoid
                |-AppTest.java
            |-resources
        |-build.gradle
      |-gradle
        |-wrapper
          |-gradle-wrapper.jar
          |-gradle-wrapper.properties
      |-gradlew
      |-gradlew.bat
      |-settings.gradle
    
  2. 의존성 추가

    app/build.gradle

    implementation 'org.springframework:spring-core:5.0.6.RELEASE'
    implementation 'org.springframework:spring-context:5.0.6.RELEASE'
    
  3. 서비스 추가

    app/src/main/java/trvoid/HelloManager.java

    package trvoid;
    
    public interface HelloManager {
        public String getServiceName();
    }
    

    app/src/main/java/trvoid/HelloManagerImpl.java

    package trvoid;
    
    public class HelloManagerImpl implements HelloManager {
        @Override
        public String getServiceName() {
            return "My Hello Service";
        }
    }
    
  4. 빈 추가

    app/src/main/java/trvoid/AppConfig.java

    package trvoid;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AppConfig {
        @Bean(name="helloService")
        public HelloManager getHelloManager() {
            return new HelloManagerImpl();
        }
    }
    
  5. 메인 클래스 수정

    app/src/main/java/trvoid/App.java

    package trvoid;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class App {
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            
            HelloManager hello = (HelloManager)context.getBean("helloService");
            
            System.out.println(hello.getServiceName());
        }
    }
    
  6. 빌드

    >gradlew build
    
  7. 실행

    >gradlew run
    

    실행 결과

    > Task :app:run
    9월 07, 2021 11:29:27 오전 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    정보: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45ff54e6: startup date [Tue Sep 07 11:29:27 KST 2021]; root of context hierarchy
    My Hello Service
    
    BUILD SUCCESSFUL in 6s
    2 actionable tasks: 2 executed
    

Written with StackEdit.

Maven + Spring 사용 기초

Maven + Spring 사용 기초

사용 환경

  • Windows 10
  • Java 1.8
  • Maven 3.8.2
  • Spring 5.0.6

Hello 프로젝트 따라하기

  1. 프로젝트 생성

    >mvn archetype:generate -DgroupId=trvoid -DartifactId=hello -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

    생성된 프로젝트 폴더 구조는 아래와 같습니다.

    hello
      |-src
        |-main
          |-java
            |-trvoid
              |-App.java
        |-test
          |-java
            |-trvoid
              |-AppTest.java
      |-pom.xml
    
  2. 의존성 추가

    pom.xml

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.6.RELEASE</version>
    </dependency>
    
  3. 서비스 추가

    src/main/java/trvoid/HelloManager.java

    package trvoid;
    
    public interface HelloManager {
        public String getServiceName();
    }
    

    src/main/java/trvoid/HelloManagerImpl.java

    package trvoid;
    
    public class HelloManagerImpl implements HelloManager {
        @Override
        public String getServiceName() {
            return "My Hello Service";
        }
    }
    
  4. 빈 추가

    src/main/java/trvoid/AppConfig.java

    package trvoid;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AppConfig {
        @Bean(name="helloService")
        public HelloManager getHelloManager() {
            return new HelloManagerImpl();
        }
    }
    
  5. 메인 클래스 수정

    src/main/java/trvoid/App.java

    package trvoid;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class App {
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            
            HelloManager hello = (HelloManager)context.getBean("helloService");
            
            System.out.println(hello.getServiceName());
        }
    }
    
  6. 컴파일

    >mvn compile
    
  7. 실행

    >mvn exec:java -Dexec.mainClass=trvoid.App
    

    실행 결과

    [INFO] Scanning for projects...
    [INFO]
    [INFO] ----------------------------< trvoid:hello >----------------------------
    [INFO] Building hello 1.0-SNAPSHOT
    [INFO] --------------------------------[ jar ]---------------------------------
    [INFO]
    [INFO] --- exec-maven-plugin:3.0.0:java (default-cli) @ hello ---
    9월 07, 2021 10:30:09 오전 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    정보: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2695bde4: startup date [Tue Sep 07 10:30:09 KST 2021]; root of context hierarchy
    My Hello Service
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  0.773 s
    [INFO] Finished at: 2021-09-07T10:30:09+09:00
    [INFO] ------------------------------------------------------------------------
    

Written with StackEdit.

국어 맞춤법 참고 자료

  제목 설명(인용) 출처 IT 글쓰기와 번역 노트 IT 기술 문서 및 서적을 집필/번역/교정하면서 얻은 경험/정보/지식을 공유합니다. 전뇌해커 [우리말 바루기] ‘대로’의 띄어쓰기 명사 뒤에서는 붙여 쓰고, 그 외에는 띄어 쓴다고 생각하면 쉽다. 다...