앱)자바 batch pid 파일 만들기

Posted by HULIA(휴리아)
2018. 4. 27. 14:34 백엔드개발/자바스프링
==main==
//pid file creation
String pidDir = System.getProperty("pid.dir", jobmgrHome+System.getProperty("file.separator")+"pid")

try{
     PidUtil pidUtil = new PidUtil(pidDir, "jobmanager.pid");
if(pidUtil.existPidFile()){
     LoggerUtil.error(logger, "already running...");
     String pid = pidUtil.readPidFile();
     LoggerUtil.error(logger,"pid: "+pid);
     System.exit(0);
}

String pid = pidUtil.createPidFile();

LoggerUtil.info(logger, "PID file created. <pid : "+pid + ">");
}catch(IOException ie){
    ie.printStackTrace();
}

}




==PidUtil==
public class PidUtil{
       private String pidDir;
       private String pidFileName;

       pulbic PidUtil(String pidDirectory, String pidFileName) {
     makeDir(pidDirectory);
     this.pidFileName = pidFileName;
     pidDir = new File(pidDirectory).getPath();
}
  

    public File getPidFile(){
           return new File(pidDir + System.getProperty("file.separator")+pidFileName);
    }

    public String getPID() throws IOException{
    String str = ManagementFactory.getRuntimeMXBean().getName();
    return str.split("@")[0];
}

public String createPidFile() throws IOException{
      String pid = null;
      pid = getPID();

      //파일 생성
      writePID(getPidFile(), pid);
      return pid;
}

public void deletePID(){
      delete(getPidFile());
}

public String readPidFile() throws IOException{
         return readFile(getPidFile());
}

public boolean existPidFile() throws IOException{
        boolean isRet = false;
//pid파일 존재하는지 체크한다.
//파일 존재할 경우 pid 정보를 읽는다
//pid가 -1인 경우 실패한 경우이므로 pid파일이 존재하지 않는다는 결과를 반환한다
//pid가 -1가 아닌 경우 windows 2000이면 tilst로 해당 pid를 체크하고 windows 2000이상이면 tasklist로 체크한다
      if(getPidFile().exist()){
          String pid = readFile(getPidFile());
         if( !pid.equals("-1")){
               String winOsName = System.getProperty("os.name");
              boolean isWindow = winOsName.startWith("Windows");
              if( isWindow) {//windows
                  if(winOsName.indexOf("2000") > -1) {
      if(hasProcess(pid, "tlist")){
              isRet = true;
       }
}else{
       if(hasProcess(pid, "tasklist")){
               isRet = false;
       }
}

              }else{//linux & unix
                 if(hasProcess(pid, "ps -p "+ pid)){
       isRet = true;
}
             }
         }
      }
      return isRet;
}

private boolean hasProcess(String pid, String checkCMD) throws IOException{
       boolean isRet = false;
       Process p_start = Runtime.getRuntime().exec(checkCMD);
       BufferedReader stdout = new BufferedReader (new InputStreamReader(p_start.getInputStream()));
        String output;
        while((output=stdout.readLine())!=null){
         if(output.indexOf(pid) > -1 && (output.startsWith("java") || output.indexOf("java") > -1)){
               isRet = true;
               break;
           }
}
p_start.destory();
return isRet;
}

private void writePID(File file, String pid) throws IOException{
     FileWriter fw = null;
     try{
           fw=new FileWriter(file);
           fw.write(pid);
           fw.close();
       }catch (IOException ioe){
            throw ioe;
       }finally{
            if(fw != null){
                 fw.close();
            }
       }
}

public synchronized void makeDir(String path){
        File dir = new File(path);
        if( !dir.exists()){
                dir.mkdirs();
        }
}

public String readFile(File file) throws IOException{
        FileReader fileReader = null;
        String s = null;
        try{
            fileReader = new FileReader(file);
            s = readReader(fileReader);
        } finally{
             if( fileReader != null){
                   fileReader.close();                
             }
        }
         return s;
}

public void delete(File file){
         if(file != null){
                 if(file.exists()){
                      file.delete();
                 }
         }
}


public String readReader(Reader input) throws IOException{
 try{
     StringBuffer buf = new StringBuffer();
     BufferedReader in = new BufferedReader(input);
     int ch;
     while((ch=in.read())!= -1){
             buf.append((char)ch);
     }
     return buf.toString();
}finally{
      input.close();
}

}
}


===우분투 스크립트(메인 스크립트)
#!/bin/bash

NAME="batch"
DEFAULT = "opt/~/env.sh"
DESC="~~~~Batch Application Serve for $NAME"

#check privilegs
if [ ' id -u' -ne 0 ]; then
     echo "You need root privileges to run this script"
     exit 1
fi

# Make sure wildfly is started with system locale
if [ -r  /etc/default/locale ]; then
           . /etc/default/locale
           export LANG
fi

# Overwrite settings from default file
if [ -f "$DEFAULT" ]; then
              . "$DEFAULT:
fi

# Setup the JVM
if [ -z "$JAVA" ]; then
          if [ -n "$JAVA_HOME" ]; then
                  JAVA="$JAVA_HOME/bin/java"
          else
                   JAVA="java"
          fi
fi


# Check if wildfly is installed
if [ ! -f "$JOBMGR_HOME/JobMnager.jar" ]; then
           log_failure_msg "$NAME is not installed in \"$JOBMGR_HOME\""
            exit 1
fi

if [ -z "$JOBMGR_USER" ]; then
            JOBMGR_USER=root
fi

# Check wilfly user
id $JOBMGR_USER > /dev/null 2>&1
if [ $? -ne 0 -o -z "$JOBMGR_USER" ]; then
            log_failure_msg "User \"$JOBMGR_USER\" does not exist..."
            exit 1
fi

# Check owner of JOBMGR_HOME
if [ ! $(stat -L -c "%U" "$JOBMGR_HOME") = $JOBMGR_USER ]; then
         log_failure_msg "The user \"$JOBMGR_USER\" is not owner of \"$JOBMGR_HOME\""
         exit 1
fi


# The amount of time to wait for startup
if [ -z "$STARTUP_WAIT" ]; then
          STARTUP_WAIT=120
fi


# The amount of time to wait for shutdown
if [ -z "$SHUTDOWN_WAIT" ]; then
            SHUTDOWN_WAIT=120
fi


# Location to keep the console log
if [ -z "JOBMGR_CONSOLE_LOG" ]; then                      JOBMGR_CONSOLE_LOG="$JOBMGR_HOME/logs/console.log"
fi

export JOBMGR_CONSOLE_LOG

touch $JOBMGR_CONSOLE_LOG
chown $JOBMGR_USER $JOBMGR_CONSOLE_LOG

# Location to set the pid file
JOBMGR_PIDFILE="$JOBMGR_HOME/pid/jobmanager.pid"
export JOBMGR_PIDFILE

# Helper functions to check status of Jboss services
check_status() {
         echo "pidofproc -p \"$JOBMGR_PIDFILE\" \"$JAVA\" >/dev/null 2>&1"
         pidofproc -p "$JOBMGR_PIDFILE" "$JAVA" >/dev/null 2>&1
}


case "$1" in
  start)
       log_daemon_msg "Starting $DESC"
       check_status
       status_start=$?
       if [ $status_start -eq 3 ]; then
              cat /dev/null > "$JOBMGR_CONSOLE_LOG"
              source $DEFAULT; java $JOBMGR_OPTS $JAVA_OPTS -jar JobManager.jar > ${JOBMGR_CONSOLE_LOG} 2>&1 &"

               count=0
               launched=0
               until [ $count -gt $STARTUP_WAIT ]
                do
                           if check_status; then
                                     launched=1
                                     break
                           fi
                           sleep 1
                            count=$((count + 1));
                  done
                 
                   if [ $launched -eq 1 ]; then
                              chown $JOBMGR_USER $(dirname "$JOBMGR_PIDFILE") || true
                   fi
                  
                   if check_status; then
                               log_end_msg 0
                   else
                               log_end_msg 1
                    fi

                    if [ $launched -eq 0 ]; then
                                log_warning_msg "$DESC hasn't started within the timeout allowed"
                                log_warning_msg "please review file \"$JOBMGR_CONSOLE_LOG\" to see the status of the service"
                     fi
       elif [ $status_start -eq 1 ]; then
                log_failure_msg "$DESC is not running but the pid file exists"
                exit 1
       elif [ $status_start -eq 0 ]; then
                log_success_msg "$DESC (already running)"
        fi   
      
     ;;



  stop)
        check_status
        status_stop=$?
        if [ $status_stop -eq 0 ]; then
                  read kpid < "$JOBMGR_PIDFILE"
                  log_daemon_msg "Stopping $DESC"
                   if check_status; then
                               kill $kpid
                   fi

                    rm "$JOBMGR_PIDFILE"
                   
                     log_end_msg 0
          elif [ $status_stop -eq 1 ]; then
                    log_action_msg "$DESC is not running but the pid file exists, cleaning up"
                    rm -f $JOBMGR_PIDFILE
           elif [ $status_stop -eq 3 ]; then
                     log_action_msg "$DESC is not running"
           fi
      ;;

  restart)
         check_status
         status_restart=$?
         if [ $status_restart -eq 0 ]; then
                       $0 stop
         fi
         $0 start

         ;;

  status)
          check_status
          status=$?
          if [ $status -eq 0 ]; then
                 read pid < $JOBMGR_PIDFILE
                 log_action_msg "$DESC is running with pid $pid"
                 exit 0
           elif [ $status -eq 1 ]; then
                 log_action_msg "$DESC is not running and the pid file exists"
                 exit 1
            elif [ $status -eq 3 ]; then
                 log_action_msg "$DESC is not running"
                 exit 3
            else
                  log_action_msg "Unable to determine $NAME status"
                 exit 4
            fi

  ;;

  *)
   log_action_msg "Usage: $0 {start|stop|restart|status}"
   exit 2
   ;;

esac

exit 0


===우분투 스크립트(env 스크립트)
env.sh파일임

#!/bin/bash


export SERVER_HOME="/opt"
export SERVER_NAME="Batch"
export JOBMGR_HOME="${SERVER_HOME}/${SERVER_NAME}"
export SERVER_TYPE="Dev"


LIB_DIR=${JOBMGR_HOME}/lib

export JAVA_HOME=/opt/java
export CLASSPATH=.:/opt/java/jre/lib:$LIB_DIR

export PATH=$JAVA_HOME/bin:$PATH

if [ "x$JOBMGR_OPTS" ="x" ]; then
     JOBMGR_OPTS="-Djobmanager"
     JOBMGR_OPTS="$JOBMGR_OPTS -Djobmgr.home=${JOBMGR_HOME}"
JOBMGR_OPTS="$JOBMGR_OPTS -Dserver.type=${SERVER_TYPE}"
JOBMGR_OPTS="$JOBMGR_OPTS -Djobmgr.resourcepath=file:${JOBMGR_HOME}/conf/"
fi

if [ "x$JAVA_OPTS" = "x" ]; then
        JAVA_OPTS="-server"
        JAVA_OPTS="$JAVA_OPTS -noverify"
         JAVA_OPTS="$JAVA_OPTS -Xms512m"
         JAVA_OPTS="$JAVA_OPTS -Xmx5124m"
         JAVA_OPTS="$JAVA_OPTS -XX:NewRatio=7" #전체 메모리의 3/4를 old generation 영역으로 지정
         JAVA_OPTS="$JAVA_OPTS -XX:PermSize=64m"
         JAVA_OPTS="$JAVA_OPTS -XX:MaxPermSize=128m"
         JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"  #Young Generation 영역에서 parrel로 GC를 수행하도록 한다
         JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"  #CMS Controller 활성화
         JAVA_OPTS="$JAVA_OPTS -XX:+CMSParallelRemarkEnabled"  #Remark 단계를 Parallel로 동작하도록 지정
         JAVA_OPTS="$JAVA_OPTS -XX:CMSFullGCsBeforeCompaction=0" # Concurrent Full GC는 항상 Compaction을 수반하도록 한다
         JAVA_OPTS="$JAVA_OPTS -XX:+ExplicitGCInvokesConcurrent"  #system.gc() 하더라도 CMS GC를 실행하도록 한다
         JAVA_OPTS="$JAVA_OPTS -verbose:gc"
         JAVA_OPTS="$JAVA_OPTS -Xloggc:$JOBMGR_HOME/gclog/gc_'date "+%Y%m%d%H"'.log"
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"  # GC에 대한 상세출력
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDateStamps"  # 시스템 날짜 기록
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintHeapAtGC"
         JAVA_OPTS="$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError"
         JAVA_OPTS="$JAVA_OPTS -XX:HeapDumpPath=$JOBMGR_HOME/gclog/java_pid.hprof"
         JAVA_OPTS="$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=8286"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.authenticate=false"
         JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true"
         JAVA_OPTS="$JAVA_OPTS -Dsun.lang.ClassLoader.allowArraySyntax=true"
         JAVA_OPTS="$JAVA_OPTS -Dsun.net.inetaddr.ttl=10"
         JAVA_OPTS="$JAVA_OPTS -Dsun.net.inetaddr.negative.ttl.10"
fi


export JAVA_OPTS JOBMGR_OPTS

npm -g 옵션으로 설치시에 폴더위치

Posted by HULIA(휴리아)
2018. 4. 23. 01:21 백엔드개발/NODEJS

윈도우:

C:\Users\user\AppData\Roaming\npm\node_modules

react native 리액트 네이티브 스터디

Posted by HULIA(휴리아)
2018. 4. 15. 17:46 뒷이야기들/스터디히스토리강의

react native는

react로 android와 ios로 동시에 native코드를 만들어주는 언어를 말한다

기존에 webview형식의 아이오닉과 phonegap과 비교되는 부분이다


개발환경

-nodejs

-npm을 통해서 설치를 하기 때문에 nodejs 설치를 기본적으로 해야 한다



https://facebook.github.io/react-native/docs/getting-started.html

리액트 네이티브 관련 정리 사이트(영문)

getting started로 테스트 진행하면 됨



getting started 방식은 두가지

1. expo를 이용해서 하는 방식(이 포스팅에서 활용한 방식)

2. 네이티브 code로 하는방식(이 포스팅에 기록하지 않음)



create-react-native-app 으로 프로젝트 생성시에 

npm-cli.js관련 오류나면

npm update후에 다시 진행하면 정상적으로 됨


만들어진 프로젝트에서 npm start를 하면 QR code가 뜨고 되고

expo.io에서 계정 생성후 스마트폰에서 expo관련 앱을 설치하고 앱에서 QR code를 찍으면 해당 페이지가 뜨게 된다


expo의 역할

-js파일로 빌드(리액트 네이티브 코드를 js파일로 변환)

-js파일을 웹페이지에 보여주는 역할(웹서버 역할)


리액트 네이티브 앱을 만들기 위해서 알아야 할 점

-반응형 웹관련

-css3 flex box layout로 검색해서 flex layout에 대해서 알아야 한다

정식명칭 css3 flexible box layout 

한글번역

:https://developer.mozilla.org/ko/docs/Web/CSS/CSS_Flexible_Box_Layout/Flexbox%EC%9D%98_%EA%B8%B0%EB%B3%B8_%EA%B0%9C%EB%85%90

https://developer.mozilla.org/ko/docs/Web/CSS/CSS_Flexible_Box_Layout

영어

:https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox

https://developer.mozilla.org/en-US/docs/Web/CSS/flex



*****쉽게 리액트 네이트브 앱을 실행할수 있는 방법(웹IDE로 리액티 네이티브 앱을 만들어 보기)

https://snack.expo.io에서 접속하면 웹 IDE가 생성되고 

run on device를 클릭하면 QR code가 뜨고

스마트폰에서 expo앱에서 QR code를 찍으면 실행된다

https://expo.io/snacks/@kimjaeeon


expo -> device 

https://docs.expo.io/versions/v27.0.0/introduction/project-lifecycle



무료 강의(영어)

https://academy.nomadcoders.co/courses/

https://programmers.co.kr/learn


리액트 네이티브 구조(한글 초보자용)

https://g6ling.gitbooks.io/react-native-tutorial-korean/content/chapter1.html


스위퍼 샘플소스

https://github.com/leecade/react-native-swiper



리액트 네이티브 한글 번역

https://seongbin9786.github.io/2018/02/10/%EB%A6%AC%EC%95%A1%ED%8A%B8%20%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0%207%20(SPA%201)/


리액트 네이티브 코드 재사용법

https://github.com/seongbin9786/reusable-react-code-examples


리액트 네이티브 기본 설명

https://github.com/seongbin9786/react-basic



react native를 사용한 초간단 커뮤니티 앱 제작

https://www.slideshare.net/taggon/react-native



https://velopert.com/3631

리액트 라이프사이클


react native app.js components 관련으로 구글 검색


부트스트랩처럼 UI객체들을 쉽게 편하게 쓸수 있는 모음

https://react-native-training.github.io/react-native-elements/docs/card.html


라이더스앱 IOS 개발기

http://woowabros.github.io/experience/2018/05/19/build-app-by-react-native.html


리액트 패턴 정리사이트

https://reactpatterns.com/


import, export 관련 내용

https://github.com/seongbin9786/es6-modules


리덕스 관련 정리

https://docs.google.com/document/d/1XSKQ7F9KtgVbJj3YM9KhieHLKrS92hD79pixNJM0mR8/edit?usp=sharing


IOS스크린샷 생성툴

https://app.shotbot.io/#/project


naivecoin 변역사이트

https://newpouy.github.io/


goalPlan 1인개발 관련 히스토리 정리

https://m.blog.naver.com/PostView.nhn?blogId=hidejj79&logNo=221256652881&proxyReferer=http%3A%2F%2Fm.facebook.com


리액트에서 주로 사용하는 디자인 패턴

https://krasimir.gitbooks.io/react-in-patterns/content/


React.js관련

https://velopert.com/reactjs-tutorials


세미나 정리

https://trello.com/b/XNk2ruv5/%EC%A2%8B%EC%95%98%EC%9D%84%EA%B1%B8-%EB%A6%AC%EC%95%A1%ED%8A%B8

Do it Vue.js 입문 정리5

Posted by HULIA(휴리아)
2018. 4. 15. 02:01 프론트엔드/자바스크립트

vue 템플릿은 

HTML, CSS 등의 마크업 속성과 vue 인스턴스에서 정의한 데이터 및 로직들을 연결하여 사용자가 브라우저에서 볼수 있는 형태의 HTML로 변환해 주는 속성입니다


템플릿 속성을 사용하는 방법은 두가지

-ES5에서 vue 인스턴스 template 속성 활용

-싱글 파일 컴포넌트 체계의 <template> 코드를 활용하는 방법


ES5에서 template 속성

  <script>

      new Vue({

             template:'<p>HELLO{{message}}</p>'

      });

    </script>



template 속성에 대해 한가지 알아둘 특징

사용자가 볼수 없지만 라이브러리 내부적으로 template 속성에서 정의한 마크업+ vue 데이터를 가상 돔 기반의 render()함수로 변환합니다

변환된 render()함수는 최종적으로 사용자가 볼 수 있게 화면을 그리는 역할을 합니다

그리고 변환 과정에서 뷰의 반응성이 화면에 더해집니다


render()함수에 익숙하다면 직접 구현해도 됩니다

JSX기반의 render()함수에 더 익숙한 리액트 개발자라면 template속성을 이용하지 않고 render() 함수를 사용해 화면 요소를 동일하게 구현할 수 있습니다

하지만 vue 프레임워크 특징 자체가 JSX나 render()함수를 모르는 사람들도 쉽게 HTML를 이용하여 개발할 수 있게 하는 것을 목표로 하기 때문에 template 속성을 사용하도록 권하고 있습니다

추후에 뷰의 반응성과 가상 돔에 대해 충분히 이해하고 나면 render()함수를 직접 구현할 수 있습니다

그러면 화면 요소의 동작 하나에 직접 관여할 수 있기 때문에 더 빠르게 화면을 렌더링할 수 있을 것입니다


ES6 싱글 파일 컴포넌트 체계

<template>

      <p>HELLO {{message}} </p>

</template>


template에서 사용하는 vue의 속성과 문법은 다음과 같습니다

-데이터 바인딩

-자바스크립트 표현식

-디렉티브

-이벤트 처리

-고급 템플릿 기법


데이터 바인딩

:HTML 화면 요소를 vue 인스턴스의 데이터와 연결하는 것을 의미

주요 문법으로는 {{}}문법과 v-bind속성이 있습니다


{{}}는 vue 인스턴스의 데이터를 HTML태그에 연결하는 가장 기본적인 텍스트 삽입 방식입니다

vue 뿐만 아니라 다른 언어나 프레임워크에서도 자주 사용되는 템플릿 문법입니다


v-bind

아이디, 클래스, 스타일 등의 HTML속성값에 vue 데이터 값을 연결할 때 사용하는 데이터 연결 방식입니다

형식은 v-bind속성으로 지정할 HTML속성이나 props속성 앞에 접두사로 붙여줍니다.


   <div id="app">

      <p v-bind:id="idA">아이디 바인딩</p>

      <p v-bind:class="classA">클래스 바인딩</p>

      <p v-bind:style="styleA">스타일 바인딩</p>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          idA: 10,

          classA: 'container',

          styleA: 'color: blue'

        }

      });

    </script>



vue 템플릿에서도 자바스크립트 표현식 쓸수 있습니다

   <div id="app">

      <p>{{ message }}</p>

      <p>{{ message + "!!!" }}</p>

      <p>{{ message.split('').reverse().join('') }}</p>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          message: 'Hello Vue.js!'

        }

      });

    </script>



자바스크립트 표현식에서 주의할 점

첫째, 자바스크립트의 선언문과 분기 구문은 사용할 수 없습니다

둘째, 복잡한 연산은 인스턴스 안에서 처리하고 화면에는 간단한 연산결과만 표시해야 합니다.

    <div id="app">

      <!-- 1. -->

      {{ var a = 10; }} <!-- X, 선언문은 사용 불가능 -->

      {{ if (true) {return 100} }} <!-- X, 분기 구문은 사용 불가능 -->

      {{ true ? 100 : 0 }} <!-- O, 삼항 연산자로 표현 가능 -->


      <!-- 2. -->

      {{ message.split('').reverse().join('') }} <!-- X, 복잡한 연산은 인스턴스 안에서 수행 -->

      {{ reversedMessage }} <!-- O, 스크립트에서 computed 속성으로 계산 후 최종 값만 표현 -->

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          message: 'Hello Vue.js!'

        },

        computed: {

          reversedMessage: function() {

            return this.message.split('').reverse().join('');

          }

        }

      });

    </script>


또한 반복적인 연산에 대해서는 미리 계산하여 저장해 놓고, 필요할 때 바로 불러오는 캐싱효과를 얻을 수 있습니다



디렉티브

:vue 디렉티브란 HTML 태그 안에 v-접두사를 가지는 모든 속성들을 의미합니다.

앞에서 배운 v-bind속성도 디렉티브에 해당합니다.


디렉티브 형식은 다음과 같습니다

<a v-if="flag">두잇 vue.js</a>


디렉티브는 화면의 요소를 더 쉽게 조작하기 위해 사용하는 기능

vue의 데이터 값이 변경되었을때 화면의 요소들이 리액티브하게 반응하여 변경된 데이터 값에 따라 갱신됩니다

이런식으로 화면의 요소를 직접 제어할 필요없이 뷰의 디렉티브를 활용하여 화면 요소들을 조작할 수 있습니다



동적인 웹 앱을 구현할때 자주 사용하는 주요 디렉티브

v-if

: 지정한 뷰 데이터의 값의 참, 거짓 여부에 따라 해당 HTML태그를 화면에 표시하거나 표시하지 않습니다


v-for

:지정한 뷰 데이터의 개수만큼 해당 HTML태그를 반복 출력합니다


v-show

:v-if와 유사하게 데이터의 진위 여부에 따라 해당 HTML 태그를 화면에 표시하거나 표시하지 않습니다

다만 v-if는 해당 태그를 완전히 삭제하지만 v-show는 css 효과만 display:none으로 주어 실제 태그는 남아있고 화면상으로만 보이지 않습니다


v-bind

:HTML태그의 기본 속성과 vue 데이터 속성을 연결합니다


v-on

:화면 요소의 이벤트를 감지하여 처리할 때 사용합니다. 예를 들어 v-on:click은 해당 태그의 클릭 이벤트를 감지하여 특정 메소드를 실행 할 수 있습니다


v-model

:폼(form)에서 주로 사용되는 속성입니다. 폼에 입력한 값을 vue 인스턴스의 데이터와 즉시 동기화합니다. 화면에 입력된 값을 저장하여 서버에 보내거나 watch와 같은 고급 속성을 이용하여 추가 로직을 수행할 수 있습니다. <input>, <select>, <textarea> 태그에만 사용할 수 있습니다


디렉티브 예제

   <div id="app">

      <a v-if="flag">두잇 Vue.js</a>

      <ul>

        <li v-for="system in systems">{{ system }}</li>

      </ul>

      <p v-show="flag">두잇 Vue.js</p>

      <h5 v-bind:id="uid">뷰 입문서</h5>

      <button v-on:click="popupAlert">경고 창 버튼</button>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          flag: true,

          systems: ['android', 'ios', 'window'],

          uid: 10

        },

        methods: {

          popupAlert: function() {

            return alert('경고 창 표시');

          }

        }

      });

    </script>




앵귤러 디렉티브와 vue 디렉티브

앵귤러에서 사용하는 디렉티브 역시 vue의 디렉티브와 비슷한 역할을 합니다

개발자가 돔 요소를 직접 제어하지 않고 프레임워크에 돔 요소 제어 권한을 위임하는 것

물론 필요에 따라 앵귤러나 뷰 모두 개발자가 직접 돔 요소에 접근할 수 있지만 프레임워크에서 권하지 않습니다.

또한 앵귤러와 vue 모두 형식과 기느을 직접 제작해서 사용할 수 있습니다.



이벤트처리

:v-on디렉티브와 methods속성을 활용

제이쿼리 못지않게 vue도 이벤트 처리가 매우 간단합니다

    <div id="app">

      <button v-on:click="clickBtn">클릭</button>

</div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        methods: {

          clickBtn: function() {

            alert('clicked');

          }

        }

      });

    </script>



v-on 디렉티브로 메스드를 호출할때 인자값을 넘기는 방법

    <div id="app">

      <button v-on:click="clickBtn(10)">클릭</button>

</div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        methods: {

          clickBtn: function(num) {

            alert('clicked ' + num + ' times');

          }

        }

      });

    </script>



event 인자를 이용해 화면 요소의 돔 이벤트에 접근

   <div id="app">

      <button v-on:click="clickBtn">클릭</button>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        methods: {

          clickBtn: function(event) {

            console.log(event);

          }

        }

      });

    </script>



고급 템플릿 기법

고급 템플릿 기법은 실제 애플리케이션을 개발할때 유용한 속성

데이터 바인딩, 디렉티브와 같은 기본적인 문법과 함께 사용


computed 속성

데이터를 가공하는 등의 복잡한 연산은 vue 인스턴스 안에서 하고 

최종적으로 HTML에는 데이터를 표현만 해야 함

computed 속성은 이러한 데이터 연산들을 정의하는 영역임


computed 속성의 첫번째 장점

data 속성 값의 변화에 따라 자동으로 다시 연산한다는 점


computed의 속성의 두번째 장점

캐싱(동일한 연산을 반복해서 하지 않기 위해 연산의 결과 값을 미리 저장하고 있다가 필요할 때 불러오는 동작)



computed속성과 methods 속성의 차이점

methods속성은 호출할때만 해당 로직이 수행되고, 

computed속성은 대상 데이터의 값이 변경되면 자동적으로 수행된다는 것

다시 말해 수동적으로 데이터를 갱신하느냐, 능동적으로 데이터를 갱신하느냐의 차이점

methods는 캐싱을 하지 않고 computed는 캐싱을 함

따라서 복잡한 연산을 반복 수행해서 화면에 나타내야 한다면 computed 속성을 이용하는 것이 methods 속성을 이용하는 것보다 성능면에서 효율적임


<div id="app">

      <p>{{ message }}</p>

      <button v-on:click="reverseMsg">문자열 역순</button>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          message: 'Hello Vue.js!'

        },

        methods: {

          reverseMsg: function() {

            this.message = this.message.split('').reverse().join('');

            return this.message;

          }

        }

      });

    </script>




watch 속성

데이터 변화를 감지하여 자동으로 특정 로직을 수행합니다

computed속성과 유사하지만 computed 속성은 내장 API를 활용한 간단한 연산 정도로 적합한 반면에

watch 속성은 데이터 호출과 같이 시간이 상대적으로 더 많이 소모되는 비동기 처리에 적합


비동기처리란?

웹 앱에서 데이터를 호출할때 일반적으로는 서버에 http 요청을 보냅니다

그런데 자바스크립트 코드가 실행되는 시점에서는 서버에 보낸 요청이 언제 응답이 올지 알수 없습니다

따라서 다른 자바스크립트 연산에 영향을 주지 못하도록 별도의 영역에서 해당 데이터를 요청하고 응답을 기다립니다.

이를 자바스크립트 비동기 처리 로직이라고 합니다


인풋박스의 입력값을 v-model 디렉티브로 연결하여 입력 값에 변화가 있을때 마다 watch속성에서 변화된 값을 로그로 출력합니다

 <div id="app">

      <input v-model="message">

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script>

      new Vue({

        el: '#app',

        data: {

          message: 'Hello Vue.js!'

        },

        watch: {

          message: function(data) {

            console.log("message의 값이 바뀝니다 : ", data);

          }

        }

      });

    </script>


v-model 디렉티브는 앵귤러의 양방향 데이터 바인딩을 본따 만든 vue의 기능

앵귤러와 동일한 방식으로 화면단의 데이터를 스크립트단의 특정 데이터와 일치시켜 줍니다




싱글 파일 컴포넌트 체계

.vue 파일로 프로젝트 구조를 구성하는 방식

확장자 .vue 파일 1개는 vue 애플리케이션을 구성하는 1개의 컴포넌트와 동일


.vue 파일의 기본구조

<template>

//HTML 태그 내용 - 화면에 표시할 요소들을 정의하는 영역(html+vue 데이터 바인딩)

</template>


<script>

export default{

//자바스크립트 내용 - vue 컴포넌트의 내용을 정의하는 영역(template, data, methods 등)

}

</script>


<style>

//css 스타일 내용 - 템플릿에 추가한 HTML태그의 CSS 스타일을 정의하는 영역

</style>


***export default{} 코드는 ES6의 자바스크립트 모듈화와 관련된 문법



앞에서 배운 싱글 파일 컴포넌트 체계를 사용하기 위해서는 .vue파일을 웹 브라우저가 인식할 수 있는 형태의 파일로 변환해 주는 웹팩이나 브라우저파이와 같은 도구가 필요합니다


웹팩은 웹 앱의 자원(HTML, CSS, 이미지)들을 자바스크립트 모듈로 변환해 하나로 묶어 웹 성능을 향상시켜 주는 자바스크립트 모듈 번들러입니다

브라우저리파이도 웹팩과 유사한 성격의 모듈 번들러이지만 웹팩과 다르게 웹 자원 압축이나 빌드 자동화 같은 기능이 없습니다


웹팩 한글 강의

https://www.infleran.com/course/webpack-웹팩-강좌/


vue 개발자들이 편하게 프로젝트를 구성할 수 있도록 CLI도구(NODEJS가 설치되어 있어야함)를 제공


CLI 설치

npm install vue-cli -global


vue CLI 명령어 템플릿

-vue init webpack

고급 웹팩 기능을 활용한 프로젝트 구성 방식, 테스팅, 문법 검사등을 지원


-vue init webpack-simple

웹팩 최소 기능을 활용한 프로젝트 구성 방식, 빠른 화면 프로토타이핑용


-vue init browserify

고급 브라우저리파이 기능을 활용한 프로젝트 구성 방식, 테스팅, 문법 검사등을 지원


-vue init browserify-simple

브라우저리파이 최소 기능을 활용한 프로젝트 구성 방식, 바른 화면 프로토타이핑용


-vue init simple

최소 vue 기능만 들어간 HTML 파일 1개 생성


-vue init pwa

웹팩 기반의 프로그레시브 웹 앱 기능을 지원하는 vue 프로젝트



vue CLI 명령어 템플릿들의 공통점

첫째, 웹팩이나 브라우저리파이 같은 모듈 번들러를 프로젝트 자체에 포함하여 바로 사용할 수 있습니다

둘째, .vue 파일을 HTML, CSS, 자바스크립트 파일로 변환해 주기 위한 vue 로더를 포함하고 있습니다.

결론적으로 .vue 파일 방식으로 애플리케이션을 개발하려면 vue 로더와 이를 지원하는 웹팩, 브라우저리파이 같은 모듈 번들러가 필요하다는 것을 알 수 있습니다


언급한 템플릿 중 웹팩과 기타 기능에 신경쓰지 않고 vue 프레임워크 자체에 가장 집중할 수 있는 템플릿은 webpack-simple

webpack 템플릿은 웹팩의 여러가지 기능과 함께 테스팅 라이브러리, 문법 검사 라이브러리를 모두 포함하고 있기 때문에 프로젝트 구성방식을 파악하는데 상당한 시간이 소요

그리고 까다로운 문법 검사로 인해 화면을 빠르게 구현하기 어려움

반면에 webpack-simple 템플릿은 vue로 개발하기 위한 웹팩의 최소 기능들만 있어 프로젝트 구성 자체가 간단합니다


vue-cli로 프로젝트 만들고 웹페이지 띄우기

0)vue-cli 설치

1)vue init 템플릿

2)npm install

3)npm run dev


vue 로더는 웹팩에서 지원하는 라이브러리입니다.

vue 로더는 싱글 파일 컴포넌트 체계에서 사용하는 .vue파일의 내용을 브라우저에서 실행 가능한 웹 페이지의 형태로 변환해 줍니다


웹팩 설정 파일의 vue 로더 속성 확인

weback.config.js파일

test는 로더가 적용될 대상파일 지정

loader는 적용할 로더의 종류를 지정


프로젝트 폴더내에서 .vue확장자를 가진 파일을 모두 선택하여 vue 로더를 적용하는 코드

그리고 .vue 파일을 선택하기 위해 자바스크립트 정규 표현식을 사용



앱)jar 파일 실행하는 법 정리

Posted by HULIA(휴리아)
2018. 4. 13. 10:16 백엔드개발/자바스프링
기본 실행방법
java -jar jar파일이름.jar

옵션 넣어서 실행방법
java -Dserver.type=Local -jar jar파일이름.jar

참고로 -jar 옵션보다 -D가 뒤에 있다면 jar파일 실행할때 옵션값을 못 가지고 가게됨

Do it Vue.js 입문 정리4

Posted by HULIA(휴리아)
2018. 4. 12. 01:55 프론트엔드/자바스크립트

웹 앱 HTTP 통신의 대표적인 사례로는 제이쿼리의 ajax가 있습니다

ajax는 서버에서 받아온 데이터를 표시할때 화면 전체를 갱신하지 않고도 화면의 일부분만 변경할수 있게 하는 자바스크립트 기법


vue에서도 ajax를 지원하기 위한 라이브러리를 제공합니다

vue 프레임워크의 필수 라이브러리로 관리하던 vue 리소스와 요즘 가장 많이 사용하는 액시오스(axios)이다


vue리소스는 초기에 코어 팀에서 공식적으로 권하는 라이브러리였으나 2016년 말에 에반이 공식적인 지원을 중단하기로 결정하면서 다시 기존에 관리했던 pageKit 팀의 라이브러리로 돌아감

그 이유는 HTTP 통신 라이브러리는 vue 라우팅, 상태 관리와 같은 라이브러리와는 다르게 프레임워크에 필수적인 기능이 아니라고 판단했기 때문



액시오스는 현재 vue 커뮤니티에서 가장 많이 사용되는 HTTP 통신 라이브러리입니다.

에반도 vue 리소스 라이브러리를 공식 라이브러리에서 제외하면서 액시오스를 언급


액시오스는 promise기반의 api 형식이 다양하게 제공되어 별도의 로직을 구현할 필요 없이 주어진 API만으로도 간편하게 원하는 로직을 구현할 수 있습니다


promise 기반의 API 형식이란 무엇일까요?

promise란 서버에 데이터를 요청하여 받아오는 동작과 같은 비동기 로직 처리에 유용한 자바스크립트 객체입니다

자바스크립트는 단일 스레드로 코드를 처리하기 때문에 특정 로직의 처리가 끝날때까지 기다려주지 않습니다.

따라서 데이터를 요청하고 받을때까지 기다렸다가 화면에 나타내는 로직을 실행해야 할 때 주로 promise를 활용합니다

그리고 데이터를 받아왔을때 promise로 데이터를 화면에 표시하거나 연산을 수행하는 등 특정로직을 수행합니다


데이터 통신과 관련한 여러 라이브러리 대부분에서 promise를 활용하고 있으며, 액시오스에서도 promise기반의 API를 지원함


액시오스 공식 리포지토리

https://github.com/axios/axios

예제와 안내 잘 되어 있음


엑시오스 설치 CDN

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


엑시오스 설치 NPM(ES6)

https://github.com/axios/axios#installing



//HTTP GET 요청

axios.get('url주소').then().catch();

--> 해당 url주소에 대해 HTTP GET 요청을 보냅니다.

서버에서 보낸 데이터를 정상적으로 받아오면 then()안에 정의한 로직이 실행되고,

데이터를 받아올때 오류가 발생하면 catch()에 정의한 로직이 수행됩니다


//HTTP POST 요청

axios.post('url주소').then().catch();

--> 해당 url주소에 대해 HTTP POST 요청을 보냅니다. then()과 catch()의 동작은 위에서 살펴본 내용과 동일합니다


//HTTP 요청에 대한 옵션 속성 정의

axios({

    method:'get',

    url:'url주소',

    ...

});

-->HTTP 요청에 대한 자세한 속성들을 직접 정의하여 보낼수 있습니다. 데이터 요청을 보낼때 URL, HTTP요청방식, 보내는 데이터유형, 기타 등등


더 많은 형식은

https://github.com/axios/axios#axios-api


예제

<div id="app">

<button v-on:click="getData">프레임워크 목록 가져오기</button>

</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>

new Vue({

el: '#app',

methods: {

getData: function() {

axios.get('https://raw.githubusercontent.com/joshua1988/doit-vuejs/master/data/demo.json')

.then(function(response) {

console.log(response);

});

}

}

});

</script>



'프론트엔드 > 자바스크립트' 카테고리의 다른 글

앱)자바스크립트 자릿수 체크하는 로직  (0) 2018.06.04
Do it Vue.js 입문 정리5  (0) 2018.04.15
Do it Vue.js 입문 정리3  (0) 2018.04.04
Do it Vue.js 입문 정리2  (0) 2018.04.01
Do it Vue.js 입문 정리  (0) 2018.03.31

스프링 프레임워크 메인 프로젝트 Spring framework project

Posted by HULIA(휴리아)
2018. 4. 5. 01:58 백엔드개발/자바스프링

Main Projects

1.Spring IO Platform

2.Spring Boot

3.Spring Framework

4.Spring Cloud Data Flow

5.Spring Cloud

6.Spring Data

7.Spring Integration

8.Spring Batch

9.Spring Security

10.Spring Hateoas

11.Spring Rest Docs

12.Spring Social

13.Spring Amqp

14.Spring Mobile

15.Spring For Android

16.Spring Web Flow

17.Spring Web Services

18.Spring Ldap

19.Spring Session

20.Spring Shell

21.Spring Flo

22.Spring Kafka

23.Spring Statemachine



Spring IO Platform

https://platform.spring.io/platform/

Spring IO is a cohesive, versioned platform for building modern applications. It is a modular, enterprise-grade distribution that delivers a curated set of dependencies while keeping developers in full control of deploying only the parts they need. Spring IO is 100% open source, lean, and modular.


The Spring IO platform includes Foundation Layer modules and Execution Layer domain-specific runtimes (DSRs). The Foundation layer represents the core Spring modules and associated third-party dependencies that have been harmonized to ensure a smooth development experience. The DSRs provided by the Spring IO Execution Layer dramatically simplify building production-ready, JVM-based workloads. The first release of Spring IO includes two DSRs: Spring Boot and Grails


Features

One platform, many workloads - build web, integration, batch, reactive or big data applications

Radically simplified development experience with Spring Boot

Production-ready features provided out of the box

Curated and harmonized dependencies that just work together

Modular platform that allows developers to deploy only the parts they need

Support for embedded runtimes, classic application server, and PaaS deployments

Depends only on Java SE, and supports Groovy, Grails and some Java EE

Works with your existing dependency management tools such as Maven and Gradle

The Spring IO Platform is certified to work on JDK 7 and 8*

*While the Spring IO Platform supports JDK 7 and 8, many individual Spring projects also support older JDK versions. Please refer to the [individual projects' documentation] (http://spring.io/docs) for the specific minimum requirements.



Spring Boot

https://projects.spring.io/spring-boot/

Takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible.


Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.


Features

Create stand-alone Spring applications

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Provide opinionated 'starter' POMs to simplify your Maven configuration

Automatically configure Spring whenever possible

Provide production-ready features such as metrics, health checks and externalized configuration

Absolutely no code generation and no requirement for XML configuration

The reference guide includes detailed descriptions of all the features, plus an extensive howto for common use cases.



Spring Framework

https://projects.spring.io/spring-framework/

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.


Features

Core technologies: dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP.

Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.

Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.

Spring MVC and Spring WebFlux web frameworks

Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache.

Languages: Kotlin, Groovy, dynamic languages.


Minimum requirements

JDK 8+ for Spring Framework 5.x

JDK 6+ for Spring Framework 4.x

JDK 5+ for Spring Framework 3.x



Spring Cloud Data Flow

https://cloud.spring.io/spring-cloud-dataflow/

Spring Cloud Data Flow is a toolkit for building data integration and real-time data processing pipelines.


Pipelines consist of Spring Boot apps, built using the Spring Cloud Stream or Spring Cloud Task microservice frameworks. This makes Spring Cloud Data Flow suitable for a range of data processing use cases, from import/export to event streaming and predictive analytics.


The Spring Cloud Data Flow server uses Spring Cloud Deployer, to deploy pipelines onto modern runtimes such as Cloud Foundry, Kubernetes, Apache Mesos or Apache YARN.


A selection of pre-built stream and task/batch starter apps for various data integration and processing scenarios facilitate learning and experimentation.


Custom stream and task applications, targeting different middleware or data services, can be built using the familiar Spring Boot style programming model.


A simple stream pipeline DSL makes it easy to specify which apps to deploy and how to connect outputs and inputs. A new composed task DSL was added in v1.2.


The dashboard offers a graphical editor for building new pipelines interactively, as well as views of deployable apps and running apps with metrics.


The Spring Could Data Flow server exposes a REST API for composing and deploying data pipelines. A separate shell makes it easy to work with the API from the command line.


Platform Implementations

An easy way to get started on Spring Cloud Data Flow would be to follow the platform-specific implementation links from the table below. Each of the implementations evolves in isolation with independent release cadences. It is highly recommended to review the platform-specific reference docs to learn more about the feature capabilities.


Server Type Stable Release Milestone/Snapshot Release

Local Server         1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Cloud Foundry Server 1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Kubernetes Server     1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Apache YARN Server 1.2.2.RELEASE[docs] 1.2.3.BUILD-SNAPSHOT[docs]

Apache Mesos Server 1.0.0.RELEASE[docs] 1.1.0.BUILD-SNAPSHOT[docs]



Spring Cloud

https://projects.spring.io/spring-cloud/

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer's own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.


Spring Cloud builds on Spring Boot by providing a bunch of libraries that enhance the behaviour of an application when added to the classpath. You can take advantage of the basic default behaviour to get started really quickly, and then when you need to, you can configure or extend to create a custom solution.




Spring Data

https://projects.spring.io/spring-data/

Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. 


It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. This is an umbrella project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.


Features

Powerful repository and custom object-mapping abstractions

Dynamic query derivation from repository method names

Implementation domain base classes providing basic properties

Support for transparent auditing (created, last changed)

Possibility to integrate custom repository code

Easy Spring integration via JavaConfig and custom XML namespaces

Advanced integration with Spring MVC controllers

Experimental support for cross-store persistence


Main modules

Spring Data Commons - Core Spring concepts underpinning every Spring Data project.

Spring Data Gemfire - Provides easy configuration and access to GemFire from Spring applications.

Spring Data JPA - Makes it easy to implement JPA-based repositories.

Spring Data JDBC - JDBC-based repositories.

Spring Data KeyValue - Map-based repositories and SPIs to easily build a Spring Data module for key-value stores.

Spring Data LDAP - Provides Spring Data repository support for Spring LDAP.

Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.

Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.

Spring Data Redis - Provides easy configuration and access to Redis from Spring applications.

Spring Data for Apache Cassandra - Spring Data module for Apache Cassandra.

Spring Data for Apache Solr - Spring Data module for Apache Solr.


Community modules

Spring Data Aerospike - Spring Data module for Aerospike.

Spring Data ArangoDB - Spring Data module for ArangoDB.

Spring Data Couchbase - Spring Data module for Couchbase.

Spring Data Azure DocumentDB - Spring Data module for Microsoft Azure DocumentDB.

Spring Data DynamoDB - Spring Data module for DynamoDB.

Spring Data Elasticsearch - Spring Data module for Elasticsearch.

Spring Data Hazelcast - Provides Spring Data repository support for Hazelcast.

Spring Data Jest - Spring Data for Elasticsearch based on the Jest REST client.

Spring Data Neo4j - Spring based, object-graph support and repositories for Neo4j.

Spring Data Spanner - Google Spanner support via Spring Cloud GCP.

Spring Data Vault - Vault repositories built on top of Spring Data KeyValue.


Related modules

Spring Data JDBC Extensions - Provides extensions to the JDBC support provided in the Spring Framework.

Spring for Apache Hadoop - Simplifies Apache Hadoop by providing a unified configuration model and easy to use APIs for using HDFS, MapReduce, Pig, and Hive.

Spring Content - Associate content with your Spring Data Entities and store it in a number of different stores including the File-system, S3, Database or Mongo’s GridFS.


Release train

Spring Data is an umbrella project consisting of independent projects with, in principle, different release cadences. To manage the portfolio, a BOM (Bill of Materials - see this example) is published with a curated set of dependencies on the individual project. The release trains have names, not versions, to avoid confusion with the sub-projects.


The names are an alphabetic sequence (so you can sort them chronologically) with names of famous computer scientists and software developers. When point releases of the individual projects accumulate to a critical mass, or if there is a critical bug in one of them that needs to be available to everyone, the release train will push out “service releases” with names ending “-SRX”, where “X” is a number.


Currently the release train contains the following modules:


Spring Data Commons

Spring Data JPA

Spring Data KeyValue

Spring Data LDAP

Spring Data MongoDB

Spring Data Gemfire

Spring Data for Apache Geode

Spring Data REST

Spring Data Redis

Spring Data for Apache Cassandra

Spring Data for Apache Solr

Spring Data Couchbase (community module)

Spring Data Elasticsearch (community module)

Spring Data Neo4j (community module)



Spring Integration

https://projects.spring.io/spring-integration/

Extends the Spring programming model to support the well-known Enterprise Integration Patterns. Spring Integration enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters. Those adapters provide a higher-level of abstraction over Spring's support for remoting, messaging, and scheduling. Spring Integration's primary goal is to provide a simple model for building enterprise integration solutions while maintaining the separation of concerns that is essential for producing maintainable, testable code.


Using the Spring Framework encourages developers to code using interfaces and use dependency injection (DI) to provide a Plain Old Java Object (POJO) with the dependencies it needs to perform its tasks. Spring Integration takes this concept one step further, where POJOs are wired together using a messaging paradigm and individual components may not be aware of other components in the application. Such an application is built by assembling fine-grained reusable components to form a higher level of functionality. WIth careful design, these flows can be modularized and also reused at an even higher level.


In addition to wiring together fine-grained components, Spring Integration provides a wide selection of channel adapters and gateways to communicate with external systems. Channel Adapters are used for one-way integration (send or receive); gateways are used for request/reply scenarios (inbound or outbound). For a full list of adapters and gateways, refer to the reference documentation.


The Spring Cloud Stream project builds on Spring Integration, where Spring Integration is used as an engine for message-driven microservices.


Features

Implementation of most of the Enterprise Integration Patterns

Endpoint

Channel (Point-to-point and Publish/Subscribe)

Aggregator

Filter

Transformer

Control Bus

Integration with External Systems

ReST/HTTP

FTP/SFTP

Twitter

WebServices (SOAP and ReST)

TCP/UDP

JMS

RabbitMQ

Email

The framework has extensive JMX support

Exposing framework components as MBeans

Adapters to obtain attributes from MBeans, invoke operations, send/receive notifications




Spring Batch

https://projects.spring.io/spring-batch/

A lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.



Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.


Features

Transaction management

Chunk based processing

Declarative I/O

Start/Stop/Restart

Retry/Skip

Web based administration interface (Spring Cloud Data Flow)



Spring Security

https://projects.spring.io/spring-security/

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.


Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements


Features

Comprehensive and extensible support for both Authentication and Authorization

Protection against attacks like session fixation, clickjacking, cross site request forgery, etc

Servlet API integration

Optional integration with Spring Web MVC

Much more…



Spring Hateoas

https://projects.spring.io/spring-hateoas/

Create REST representations that follow the HATEOAS principle from your Spring-based applications.


Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.


Features

Model classes for link, resource representation models

Link builder API to create links pointing to Spring MVC controller methods

Support for hypermedia formats like HAL



Spring Rest Docs

https://projects.spring.io/spring-restdocs/

Document RESTful services by combining hand-written documentation with auto-generated snippets produced with Spring MVC Test.


Spring REST Docs helps you to document RESTful services. It combines hand-written documentation written with Asciidoctor and auto-generated snippets produced with Spring MVC Test. This approach frees you from the limitations of the documentation produced by tools like Swagger. It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum of fuss.




Spring Social

https://projects.spring.io/spring-social/

Connect your Spring application with Software-as-a-Service (SaaS) API providers such as Facebook, Twitter, and LinkedIn.


SPRING SOCIAL CORE

A framework for creating connections between a Spring application and an API. Also includes support for "Sign in With [Provider]" for authenticating via an API provider.

 

SPRING SOCIAL FACEBOOK

A provider extension for Spring Social to enable connectivity with Facebook and an API binding for Facebook's Graph API.

 

SPRING SOCIAL TWITTER

A provider extension for Spring Social to enable connectivity with Twitter and an API binding for Twitter's REST API.

 

SPRING SOCIAL LINKEDIN

A provider extension for Spring Social to enable connectivity with LinkedIn and an API binding for LinkedIn's REST API.



Spring Amqp

https://projects.spring.io/spring-amqp/

The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. It provides a "template" as a high-level abstraction for sending and receiving messages. It also provides support for Message-driven POJOs with a "listener container". These libraries facilitate management of AMQP resources while promoting the use of dependency injection and declarative configuration. In all of these cases, you will see similarities to the JMS support in the Spring Framework.



The project consists of two parts; spring-amqp is the base abstraction, and spring-rabbit is the RabbitMQ implementation.


Features

Listener container for asynchronous processing of inbound messages

RabbitTemplate for sending and receiving messages

RabbitAdmin for automatically declaring queues, exchanges and bindings




Spring Mobile

https://projects.spring.io/spring-mobile/

Spring Mobile is an extension to Spring MVC that aims to simplify the development of mobile web applications.


Spring Mobile is a framework that provides capabilities to detect the type of device making a request to your Spring web site and serve alternative views based on that device. Like all Spring projects, the real power of Spring Mobile is found in how easily it can be extended.


Features

A Device resolver abstraction for server-side detection of mobile and tablet devices

Site preference management that allows the user to indicate if he or she prefers a "normal", "mobile", or "tablet" experience

A site switcher capable of switching the user to the most appropriate site, either mobile, tablet, or normal, based on his or her device and optionally indicated site preference

Device aware view management for organizing and managing different views for specific devices



Spring For Android

https://projects.spring.io/spring-android/

Spring for Android is an extension of the Spring Framework that aims to simplify the development of native Android applications.


Spring for Android is a framework that is designed to provide components of the Spring family of projects for use in Android apps. Like all Spring projects, the real power of Spring for Android is found in how easily it can be extended.


Features

A Rest Client for Android

Auth support for accessing secure APIs



Spring Web Flow

https://projects.spring.io/spring-webflow/

Spring Web Flow builds on Spring MVC and allows implementing the "flows" of a web application. A flow encapsulates a sequence of steps that guide a user through the execution of some business task. It spans multiple HTTP requests, has state, deals with transactional data, is reusable, and may be dynamic and long-running in nature..



The sweet spot for Spring Web Flow are stateful web applications with controlled navigation such as checking in for a flight, applying for a loan, shopping cart checkout, or even adding a confirmation step to a form. What these scenarios have in common is one or more of the following traits:


There is a clear start and an end point.

The user must go through a set of screens in a specific order.

The changes are not finalized until the last step.

Once complete it shouldn't be possible to repeat a transaction accidentally



Spring Web Services

https://projects.spring.io/spring-ws/

Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads.


Spring Web Services (Spring-WS) is a product of the Spring community focused on creating document-driven Web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads. The product is based on Spring itself, which means you can use the Spring concepts such as dependency injection as an integral part of your Web service.


People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks lacking when it comes to following Web service best practices. Spring-WS makes the best practice an easy practice. This includes practices such as the WS-I basic profile, Contract-First development, and having a loose coupling between contract and implementation. The other key features of Spring Web services are:


Features

Makes the Best Practice an Easy Practice: Spring Web Services makes enforcing best practices easier. This includes practices such as the WS-I basic profile, Contract-First development, and having a loose coupling between contract and implementation.

Powerful mappings: You can distribute incoming XML request to any object, depending on message payload, SOAP Action header, or an XPath expression.

XML API support: Incoming XML messages can be handled in standard JAXP APIs such as DOM, SAX, and StAX, but also JDOM, dom4j, XOM, or even marshalling technologies.

Flexible XML Marshalling: The Object/XML Mapping module in the Spring Web Services distribution supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream. And because it is a separate module, you can use it in non-Web services code as well.

Reuses your Spring expertise: Spring-WS uses Spring application contexts for all configuration, which should help Spring developers get up-to-speed nice and quickly. Also, the architecture of Spring-WS resembles that of Spring-MVC.

Supports WS-Security: WS-Security allows you to sign SOAP messages, encrypt and decrypt them, or authenticate against them.

Integrates with Acegi Security: The WS-Security implementation of Spring Web Services provides integration with Spring Security. This means you can use your existing configuration for your SOAP service as well.

Built by Maven: This assists you in effectively reusing the Spring Web Services artifacts in your own Maven-based projects.

Apache license. You can confidently use Spring-WS in your project.



Spring Ldap

https://projects.spring.io/spring-ldap/

Makes it easier to build Spring-based applications that use the Lightweight Directory Access Protocol.


Spring LDAP is a Java library for simplifying LDAP operations, based on the pattern of Spring's JdbcTemplate. The framework relieves the user of common chores, such as looking up and closing contexts, looping through results, encoding/decoding values and filters, and more.


Features

Provides LDAP template which eliminates the need to worry about creating and closing LdapContext and looping through NamingEnumeration

Comprehensive unchecked Exception hierarchy built on Spring's DataAccessException

Contains classes for dynamically building LDAP filters and Distinguished Names (DNs)

Client-side LDAP transaction management

Much more…



Spring Session

https://projects.spring.io/spring-session/

Spring Session provides an API and implementations for managing a user’s session information.


Features

Spring Session makes it trivial to support clustered sessions without being tied to an application container specific solution. It also provides transparent integration with:


HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way, with support for providing session IDs in headers to work with RESTful APIs

WebSocket - provides the ability to keep the HttpSession alive when receiving WebSocket messages

WebSession - allows replacing the Spring WebFlux’s WebSession in an application container neutral way

Modules

Spring Session consists of the following modules:


Spring Session Core - provides core Spring Session functionalities and APIs

Spring Session Data Redis - provides SessionRepository and ReactiveSessionRepository implementation backed by Redis and configuration support

Spring Session JDBC - provides SessionRepository implementation backed by a relational database and configuration support

Spring Session Hazelcast - provides SessionRepository implementation backed by Hazelcast and configuration support




Spring Shell

https://projects.spring.io/spring-shell/

The Spring Shell project provides an interactive shell that allows you to plugin your own custom commands using a Spring based programming model.


Users of the Spring Shell project can easily build a full featured shell ( aka command line) application by depending on the Spring Shell jars and adding their own commands (which come as methods on spring beans). Creating a command line application can be useful e.g. to interact with your project's REST API, or to work with local file content.


Features

Spring Shell's features include


A simple, annotation driven, programming model to contribute custom commands

Use of Spring Boot auto-configuration functionality as the basis for a command plugin strategy

Tab completion, colorization, and script execution

Customization of command prompt, shell history file name, handling of results and errors

Dynamic enablement of commands based on domain specific criteria

Integration with the bean validation API

Already built-in commands, such as clear screen, gorgeous help, exit

ASCII art Tables, with formatting, alignment, fancy borders, etc.



Spring Flo

https://projects.spring.io/spring-flo/

Spring Flo is a JavaScript library that offers a basic embeddable HTML5 visual builder for pipelines and simple graphs. This library is used as the basis of the stream builder in Spring Cloud Data Flow.


Flo includes all the basic elements of an integration-flow designer such as connectors, control nodes, palettes, state transitions, and graph topologies—importantly, there is a textual shell, DSL support, and a graphical canvas designed for creating and reviewing comprehensive workflows.


Features

Create, manage, and monitor stream pipelines using DSL, a graphical canvas, or both

Write pipelines via DSL with content-assist and auto-complete

See a visual representation of modules across a distributed deployment

Use auto-adjustment and grid-layout capabilities in the GUI for easier and more efficient organization of pipelines



Spring Kafka

https://projects.spring.io/spring-kafka/

The Spring for Apache Kafka (spring-kafka) project applies core Spring concepts to the development of Kafka-based messaging solutions. It provides a "template" as a high-level abstraction for sending messages. It also provides support for Message-driven POJOs with @KafkaListener annotations and a "listener container". These libraries promote the use of dependency injection and declarative. In all of these cases, you will see similarities to the JMS support in the Spring Framework and RabbitMQ support in Spring AMQP.


Features

KafkaTemplate

KafkaMessageListenerContainer

@KafkaListener

KafkaTransactionManager

spring-kafka-test jar with embedded kafka server




Spring Statemachine

https://projects.spring.io/spring-statemachine/

Spring Statemachine is a framework for application developers to use state machine concepts with Spring applications.

Spring Statemachine aims to provide following features:

Easy to use flat one level state machine for simple use cases.
Hierarchical state machine structure to ease complex state configuration.
State machine regions to provide even more complex state configurations.
Usage of triggers, transitions, guards and actions.
Type safe configuration adapter.
Builder pattern for easy instantiation for use outside of Spring Application context
Recipes for usual use cases
Distributed state machine based on a Zookeeper
State machine event listeners.
UML Eclipse Papyrus modeling.
Store machine config in a persistent storage.
Spring IOC integration to associate beans with a state machine.
State machines are powerful because behaviour is always guaranteed to be consistent, making it relatively easy to debug. This is because operational rules are written in stone when the machine is started. The idea is that your application may exist in a finite number of states and certain predefined triggers can take your application from one state to the next. Such triggers can be based on either events or timers.

It is much easier to define high level logic outside of your application and then rely on the state machine to manage state. You can interact with the state machine by sending an event, listening for changes or simply request a current state.

Do you want to ask a question? Go to StackOverflow and use a tag spring-statemachine or Gitter.


앱)logback.xml sample example

Posted by HULIA(휴리아)
2018. 4. 4. 15:39 백엔드개발/자바스프링
<?xml version"1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="1 seconds">

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
         <encoder>
                <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}][%-5level][%logger] %msg%n</pattern>
         </endcoder>
</appender>

<appender name="SERVICE_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>c:/test/service.log.%d{yyyy-MM-dd-HH}</fileNamePattern>
      </rollingPolicy>
      <encoder>
                 <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}][%-5level][%logger] %msg%n</pattern>
      </encoder>
</appender>

<root level="INFO">
         <appender-ref ref="CONSOLE" />
         <appender-ref ref="SERVICE_LOG" />
</root>


<logger name="SERVICE_LOGGER" level="DEBUG" additivity="false">
       <appender-ref ref="CONSOLE" />
</logger>

</configuration>

Do it Vue.js 입문 정리3

Posted by HULIA(휴리아)
2018. 4. 4. 00:06 프론트엔드/자바스크립트

라우팅이란

웹페이지간의 이동방법을 말함


라우팅은 현대 웹 앱 형태 중 하나인 싱글 페이지 애플리케이션에서 주로 사용하고 있습니다

브라우저에서 웹페이지를 요청하면 서버에서 응답을 받아 웹페이지를 다시 사용자에게 보여주는 준비를 하는 시간동안 깜박이는데 라우팅으로 처리하면 깜빡거림 없이 화면을 전환할 수 있을뿐 아니라 더 빠르게 화면을 조작할 수 있음


싱글 페이지 애플리케이션:

페이지를 이동할때마다 서버에 웹페이지를 요청하여 새로 갱신하는 것이 아니라 미리 해당 페이지들을 받아 놓고 페이지 이동시에 클라이언트의 라우팅을 이용하여 화면을 갱신하는 패턴을 적용한 애플리케이션


Vue뿐만 아니라 리액트나 앵귤러 모두 라우팅을 이용하여 화면을 전환하고 있음


프런트엔드 프레임워크를 사용하지 않고 일반 HTML 파일들로도 라우팅 자바스크립트 라이브러리를 이용하여 라우팅 방식의 페이지 이동을 구현할 수 있음

대표적인 라우팅 라이브러리

router.js와 navigo.js가 있음



vue라우터

vue 라우터는 vue에서 라우팅 기능을 구현할 수 있도록 지원하는 공식 라이브러리

vue 라우터를 이용하여 vue로 만든 페이지 간에 자유롭게 이동가능


vue 라우터 태그와 기능

<router-link to="URL값"> : 페이지 이동 태그, 화면에서는 <a>로 표시되며 클릭하면 to에 지정한 url로 이동합니다

<router-view> : 페이지 표시 태그, 변경되는 url에 따라 해당 컴포넌트를 뿌려주는 영역입니다


===기본 vue 라우터 예시===

    <div id="app">

      <h1>뷰 라우터 예제</h1>

      <p>

        <router-link to="/main">Main 컴포넌트로 이동</router-link>

        <router-link to="/login">Login 컴포넌트로 이동</router-link>

      </p>

      <router-view></router-view>

    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script src="https://unpkg.com/vue-router@3.0.1/dist/vue-router.js"></script>

    <script>

      // 3. Main. Login 컴포넌트 내용 정의

      var Main = { template: '<div>main</div>' };

      var Login = { template: '<div>login</div>' };


      // 4. 각 url에 해당하는 컴포넌트 등록

      var routes = [

        { path: '/main', component: Main },

        { path: '/login', component: Login }

      ];


      // 5. 뷰 라우터 정의

      var router = new VueRouter({

        routes

      });


      // 6. 뷰 라우터를 인스턴스에 등록

      var app = new Vue({

        router

      }).$mount('#app');

    </script>




$mount() API는 el속성과 동일하게 인스턴스를 화면에 붙이는 역할을 합니다.

인스턴스를 생성할때 el속성을 넣지 않았더라도 생성하고 나서 $mount()를 이용하면 강제로 인스턴스를 화면에 붙일 수가 있습니다.

참고로, 뷰 라우터의 공식 문서는 모두 인스턴스 안에 el를 지정하지 않고 라우터만 지정하여 생성한 다음 생성된 인스턴스를 $mount()를 이용해 붙이는 식으로 안내하고 있습니다.



라우터 URL의 해시값을 없애는 방법

vue 라우터의 기본 url 형식은 해시값을 사용합니다

만약index.html/login과 같이 해시값을 없애고 싶으면 오른쪽처럼 히스토리 모드(history mode)를 활용하면 됩니다

var router = new VueRouter({

     mode:'history',

     routes

});




네스티드 라우터

   <div id="app">

      <router-view></router-view>

    </div>



 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script src="https://unpkg.com/vue-router@3.0.1/dist/vue-router.js"></script>

    <script>

      var User = {

        template: `

          <div>

            User Component

            <router-view></router-view>

          </div>

        `

      };

      var UserProfile = { template: '<p>User Profile Component</p>' };

      var UserPost = { template: '<p>User Post Component</p>' };


      var routes = [

        {

          path: '/user',

          component: User,

          children: [

            {

              path: 'posts',

              component: UserPost

            },

            {

              path: 'profile',

              component: UserProfile

            },

          ]

        }

      ];


      var router = new VueRouter({

        routes

      });


      var app = new Vue({

        router

      }).$mount('#app');

    </script>





네임드 뷰(특정 페이지로 이동했을 때 해당 URL에 맞추어 여러개의 컴포넌트를 한번에 표시가능)

    <div id="app">

      <router-view name="header"></router-view>

      <router-view></router-view>

      <router-view name="footer"></router-view>

    </div>



    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>

    <script src="https://unpkg.com/vue-router@3.0.1/dist/vue-router.js"></script>

    <script>

      var Body = { template: '<div>This is Body</div>' };

      var Header = { template: '<div>This is Header</div>' };

      var Footer = { template: '<div>This is Footer</div>' };


      var router = new VueRouter({

        routes: [

          {

            path: '/',

            components: {

              default: Body,

              header: Header,

              footer: Footer

            }

          }

        ]

      })


      var app = new Vue({

        router

      }).$mount('#app');

    </script>




<router-view>에서 사용한 name속성은 예약어가 아니라 사용자가 임의로 정의할 수 있는 값

위에서 사용한 header, footer 값 모두 appHeader, appFooter라고 이름을 변경해도 동일하게 동작함

예외적으로 name속성을 지정하지 않았을때의 기본 컴포넌트는 default로 접근함



'프론트엔드 > 자바스크립트' 카테고리의 다른 글

Do it Vue.js 입문 정리5  (0) 2018.04.15
Do it Vue.js 입문 정리4  (1) 2018.04.12
Do it Vue.js 입문 정리2  (0) 2018.04.01
Do it Vue.js 입문 정리  (0) 2018.03.31
클린코드 자바 스크립트  (0) 2018.03.01

스프링부트 swagger ui 추가하기 API 설명 웹 페이지

Posted by HULIA(휴리아)
2018. 4. 3. 22:55 백엔드개발/스프링부트

pom.xml

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.3.1</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.3.1</version>

</dependency>



springbootapliction main 클래스에

@SpringBootApplication

@EnableSwagger2


추가해주면 자동으로 API관련된 정보들이 들어가게 됨




@Configuration

@EnableSwagger2

public class SwaggerConfig {

@Bean

public UiConfiguration uiConfig() {

return UiConfiguration.DEFAULT;

}

private ApiInfo metadata() {

return new ApiInfoBuilder()

.title("Spring Boot")

.description("Spring boot REST API")

.version("1.0")

.build();

}

@Bean

public Docket api() {

return new Docket(DocumentationType.SWAGGER_2)

.select()

.apis(RequestHandlerSelectors.any())

//.paths(PathSelectors.any()) // 모든 클래스 다 나옴

.paths(PathSelectors.ant("/test/**")) // 정해진 클래스만 나오도록 함

.build()

.apiInfo(metadata());

}

}

이렇게 Config클래스를 만들어서 설정해주면 세팅이 됨~



추가적으로 swagger 페이지에 API문서를 더 자세히 적고 싶으면 어노테이션을 추가로 하면 작성하면 된답니다

https://github.com/swagger-api/swagger-core/wiki/Annotations



사용예시사이트

https://steemit.com/kr-dev/@igna84/spring-boot-web-swagger

https://jojoldu.tistory.com/31