본문 바로가기

아카이브/Spring

[유틸] RestAPI model,dto,controller 파일 자동 생성(Mybatis)

1. 코드

package com.jusunja.jusunja.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class MkdirAndFileUtil {
    static Boolean flag = true;
    static ArrayList<File> filear = new ArrayList<>();
    static ArrayList<String> folderar = new ArrayList<>();
    public static void main(String[] args) {

        final String BASEPATH = MkdirAndFileUtil.class.getResource("..").getPath().replace("target/classes",
                "src/main/java");
        System.out.println("BASEURL : " + BASEPATH);

        Scanner sc = new Scanner(System.in);
        System.out.println("클래스명을 입력하세요.");
        String CLASSNAME = sc.nextLine();
       
        // final String CLASSNAME = "User";
        
        String[] foldername = new String[4];
        
        String CLASSNAMEARR[] = CLASSNAME.split("/");
        if(CLASSNAMEARR.length > 1){
            
            foldername[0] = "controller"+"/"+CLASSNAME.replace("/"+CLASSNAMEARR[CLASSNAMEARR.length-1], "").toLowerCase();
            foldername[1] = "model"+"/"+CLASSNAME.replace("/"+CLASSNAMEARR[CLASSNAMEARR.length-1], "").toLowerCase();
            foldername[2] = "dao"+"/"+CLASSNAME.replace("/"+CLASSNAMEARR[CLASSNAMEARR.length-1], "").toLowerCase();
            foldername[3] = "service"+"/"+CLASSNAME.replace("/"+CLASSNAMEARR[CLASSNAMEARR.length-1], "").toLowerCase();
            CLASSNAME = CLASSNAMEARR[CLASSNAMEARR.length-1];
            flag = false;
        }else{
            foldername[0] = "controller";
            foldername[1] = "model";
            foldername[2] = "dao";
            foldername[3] = "service";
        }

        for (int i = 0; i < foldername.length; i++) {
            String path = "";
            if(flag){
                path = BASEPATH + foldername[i] + "/" + CLASSNAME.toLowerCase();
            }
            else{
                path = BASEPATH + foldername[i];
            }
            
            if (foldername[i].contains("controller")) {
                mkdir(path, CLASSNAME + "Controller.java");
            } else if (foldername[i].contains("model")) {
                mkdir(path, CLASSNAME + "VO.java");
            } else if (foldername[i].contains("dao")) {
                mkdir(path, CLASSNAME + "DAO.java");
                // Impl
                path += "/Impl";
                mkdir(path, CLASSNAME + "DAOImpl.java");
            } else if (foldername[i].contains("service")) {
                mkdir(path, CLASSNAME + "Service.java");
                // Impl
                path += "/Impl";
                mkdir(path, CLASSNAME + "ServiceImpl.java");
            }
        }


        System.out.println("삭제하시겠습니까? N : 0 Y : 1");
        int result = sc.nextInt();
        if(result == 1){
            rmfile();    
        }

        sc.close();
    }

    private static void rmfile(){
        for(File file : filear){
            file.delete();
        }

        for(String folderpath : folderar){
            
            
            String[] patharr = folderpath.split("/");
            
            Loop1 :
            for (int i = patharr.length - 1; i > 0; i--) {
                String rmpath = "";
                for (int j = 0; j <= i; j++) {
                    rmpath+="/"+patharr[j];

                    if(patharr[i].equals("controller")){
                        break Loop1;
                    }
                    else if(patharr[i].equals("model")){
                        break Loop1;
                    }
                    else if(patharr[i].equals("dao")){
                        break Loop1;
                    }
                    else if(patharr[i].equals("service")){
                        break Loop1;
                    }
                }
                File file = new File(rmpath);
                if(file.delete() == false){
                    break;
                }

                
            }
        }
    }

    private static void mkdir(String path, String filename) {

        File Folder = new File(path);
        if (!Folder.exists()) {
            try {
                Folder.mkdirs(); // 폴더 생성합니다.
                folderar.add(path);
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
        else {
            
        }
        

        File file = new File(path + File.separator + filename);
        filear.add(file);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {

            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);

            filename = filename.split("\\.")[0];
            String packagename = "package "
                    + path.substring(path.indexOf("java") + 5, path.length()).replaceAll("/", ".") + ";\n";
            String imports = "";

            String annotation = "";

            
            String mkclassstart = "public class " + filename + "{\n";
            String classcontent = "";
            String mkclassend = "}";

            if (filename.contains("Controller")) {

                String servicename = filename.replace("Controller", "Service");

                imports = "import org.springframework.web.bind.annotation.CrossOrigin;\n";
                imports += "import org.springframework.web.bind.annotation.RestController;\n";
                imports += "import org.springframework.beans.factory.annotation.Autowired;\n";
                imports += packagename.replace("package", "import").replace("controller", "service").replace("\n", "").replace(";", "")
                +"."+servicename+";\n";
                imports += "import org.springframework.web.bind.annotation.GetMapping;\n";
                imports += "import org.springframework.web.bind.annotation.PostMapping;\n";
                imports += "import org.springframework.http.HttpStatus;\n";
                imports += "import org.springframework.http.ResponseEntity;\n";
                imports += "import org.springframework.web.bind.annotation.RequestParam;\n";
                imports += "import org.springframework.web.bind.annotation.RequestBody;\n";

                annotation = "@CrossOrigin(origins = { \"*\" },maxAge = 6000)\n";
                annotation += "@RestController";

                classcontent = "\t@Autowired\n";
                classcontent += "\t"+servicename + " "+servicename.toLowerCase()+";\n\n";
                classcontent += "\t/*\n";
                classcontent += "\t@GetMapping(value=\"path\")\n";
                classcontent += "\tpublic ResponseEntity<Object> getMethodName(@RequestParam String param) {\n";
                classcontent += "\treturn new ResponseEntity<>(\"success\", HttpStatus.OK);\n";
                classcontent += "\t}\n";
                classcontent += "\t@PostMapping(value=\"path\")\n";
                classcontent += "\tpublic ResponseEntity<Object> postMethodName(@RequestBody SomeEnityData entity) {\n";
                classcontent += "\treturn new ResponseEntity<>(\"success\", HttpStatus.OK);\n";
                classcontent += "\t}\n";
                classcontent += "\t*/\n";

            } 
            else if (filename.contains("VO")) {

                imports +=  "import lombok.Data;\n";
                imports +=  "import lombok.NoArgsConstructor;\n";
                imports +=  "import lombok.ToString;";

                
                annotation = "\n@ToString\n@Data\n@NoArgsConstructor\n";
                

            } 
            else if (filename.contains("DAOImpl")) {
                // puvlic class filename implements filenamedao
                String importdao = filename.substring(0, filename.length() - 4);
                
                imports = packagename.replace("Impl", importdao).replace("package", "import");
                imports += "import org.springframework.stereotype.Repository;\n";
                imports += "import org.apache.ibatis.session.SqlSession;\n";
                imports += "import org.springframework.beans.factory.annotation.Autowired;\n";

                

                annotation = "@Repository";

                mkclassstart = "public class " + filename + " implements " + importdao + "{\n";
                classcontent = "\t@Autowired\n";
                classcontent += "\tSqlSession sqlsession;\n";

                
                
            } else if (filename.contains("DAO")) {

                mkclassstart = "public interface " + filename + "{\n";

            } else if (filename.contains("ServiceImpl")) {

                String importservice = filename.substring(0, filename.length() - 4);
                String daoautowired = importservice.replace("Service", "DAO");
                
                
                imports = packagename.replace("Impl", importservice).replace("package", "import");
                imports += "import org.springframework.stereotype.Service;\n";
                imports += "import org.springframework.beans.factory.annotation.Autowired;\n";
                imports += packagename.replace("service", "dao").replace("Impl", daoautowired).replace("package", "import");

                annotation = "@Service";
                mkclassstart = "public class " + filename + " implements " + importservice + "{\n";
                classcontent = "\t@Autowired\n";
                classcontent += "\t"+daoautowired+" "+daoautowired.toLowerCase()+";\n";


                
            } else if (filename.contains("Service")) {

                mkclassstart = "public interface " + filename + "{\n";

            }

            osw.write(packagename+"\n");
            if(imports != ""){
                osw.write(imports+"\n");
            }
            if(annotation != ""){
                osw.write(annotation+"\n");
            }
            osw.write(mkclassstart+classcontent+mkclassend);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}

 

2. 사용법

클래스명을 입력해주세요.

 

생성된 파일을 확인하세요

 

생성된 파일이 잘못되었다면 롤백하세요

 

롤백 후 빈 폴더

 

3.dependencies

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web-services</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- lombok-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

 

매번 파일만드는게 너무 귀찮아서 파일로 만들어쓰고있습니다 유용하게 사용하세요~

'아카이브 > Spring' 카테고리의 다른 글

[Spring] Fcm init  (1) 2021.07.23
[Spring] REST API 부하 테스트  (0) 2021.07.19