JSON Data를 응답하는 웹 서비스 만들기

1. gradle 셋팅

//build.gradle
plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

2. 응답 객체와 컨트롤러 생성

//Greeting.java
package com.example.restservice;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}


//GreetingController.java
package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

위 내용에 대한 세부 사항

  • @GetMaping은 RequestMapping(method=GET)과 @PostMapping은 RequestMapping(method=POST)와 동일
  • @RequestParam은 url의 query string 파라미터 중 value속성과 매칭되는 값을 해당 변수에 묶음. defaultValue 속성으로 변수의 기본값 지정.
  • @RestController는 클래스에 속하는 모든 메소드에 대해 view 대신 객체 데이터를 리턴하도록 함.
  • @RestController는 @Controller 와 @ResponseBody 두 어노테이션의 축약

@SpringBootApplication은 아래 세 어노테이션의 축약

  • @Configuration : 어노테이션이 붙은 클래스를 어플리케이션 컨텍스트에 대한 Bean 정의 소스로 지정함.
  • @EnableAutoConfiguration : 스프링부트의 meta 파일을 읽어서, 미리 정의되어 있는 자바 설정 파일(@Configuration)들을 빈으로 등록하는 역할을 수행.
  • @ComponentScan : 컴포넌트 클래스를 스캔하여 빈으로 등록해주는 역할.

main() 메소드는 어플리케이션 실행을 위해스프링부트의 SpringApplication.run() 을 사용.

출처 : spring.io/guides/gs/rest-service/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Maven  (0) 2020.11.15
Building Java Projects with Gradle  (0) 2020.10.31
Consuming a RESTful Web Service  (0) 2020.10.31
Scheduling Tasks  (0) 2020.09.06
_.countBy(collection, [iteratee=_.identity])
  • 주어진 조건으로 갯수를 셈.
_.each -> forEach
_.eachRight -> forEachRight
_.every(collection, [predicate=_.identity])
  • 모든 원소가 조건을 만족하면 true
_.filter(collection, [predicate=_.identity])
  • 주어진 조건을 만족하는 원소의 배열을 반환
_.find(collection, [predicate=_.identity], [fromIndex=0])
  • 주어진 조건을 만족하는 첫번째 원소를 찾음
_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1])
  • 주어진 조건을 만족하는 마지막 원소를 찾음
_.flatMap(collection, [iteratee=_.identity])
  • 주어진 조건으로 변환 + 직렬화한 배열 반환
_.flatMapDeep(collection, [iteratee=_.identity])
  • _.flayMap + 재귀적 직렬화_.flatMapDepth
_.flatMapDepth(collection, [iteratee=_.identity], [depth=1])
  • _.flatMap + depth만큼 직렬화
_.forEach(collection, [iteratee=_.identity])
  • 집합의 각 원소에 대해 iteratee 실행
_.forEachRight(collection, [iteratee=_.identity])
  • _.forEach + 오른쪽 원소부터 실행
_.groupBy(collection, [iteratee=_.identity])
  • iteratee를 통한 그룹
_.includes(collection, value, [fromIndex=0])
  • index부터 시작해서 집합이 값을 포함하는지 확인 (문자열일 경우 문자열이 포함하는지 확인)
_.invokeMap(collection, path, [args])
_.keyBy(collection, [iteratee=_.identity])
  • iteratee로 생성된 key로 구성된 집합 반환
_.map(collection, [iteratee=_.identity])
  • iteratee로 각 원소 변환한 집합 반환
_.orderBy(collection, [iteratees=[_.identity]], [orders])
  • _.soryBy + 키 직접 지정 가능
_.partition(collection, [predicate=_.identity])
  • 조건으로 두그룹으로 분리
_.reduce(collection, [iteratee=_.identity], [accumulator])
_.reduceRight(collection, [iteratee=_.identity], [accumulator])

 

_.reject(collection, [predicate=_.identity])
  • _.filter의 반대

 

_.sample(collection)

  • 집합 내의 무작위 원소 추출

 

_.sampleSize(collection, [n=1])
  • n개의 유니크 원소 추출

 

_.shuffle(collection)
  •  

 

_.size(collection)
  • 집합의 사이즈 추출 (문자열이면 길이)

 

_.some(collection, [predicate=_.identity])
  • 배열에 조건을 만족하는 원소가 하나라도 있는지

 

_.sortBy(collection, [iteratees=[_.identity]])
  • iteratee로 집합 정렬

 

 

 

'공식메뉴얼 > lodash' 카테고리의 다른 글

Array  (0) 2020.06.27
Lodash란?  (1) 2020.06.27
_.chunk

사용법 :  _.chunk(array, [size=N]) is the 
용도 : 배열을 원하는 크기로 나눈다.

_.compact

사용법 : _.compact(array)
용도 : false, null, 0, "", undefined, NaN 등의 falsey값을 제거한 배열을 생성한다.

_.concat

사용법 : _.concat(array, [values])
용도 : 서로 다른 숫자나, 배열을 연결시켜 새로운 배열을 만든다.

_.difference

사용법 : _.difference(array, [values])
용도 : 두 배열에서 다른 원소를 찾아낸다.

_.differenceBy

사용법 : _.differenceBy(array, [values], [iteratee=_.identity])
용도 : _.difference + iteratee

_.differenceWith

사용법 :  _.differenceWith(array, [values], [comparator])
용도 : _.difference + comparator

_.drop

사용법 : _.drop(array, [n=1])
용도 : 앞에서부터 n개 원소를 제거함

_.dropRight

사용법 : _.dropRight(array, [n=1])
용도 : 뒤에서부터 n개 원소를 제거함

_.dropRightWhile

사용법 : _.dropRightWhile(array, [predicate=_.identity])
용도 : 조건이 falsey값을 반환할 때까지 뒤에서부터 제거

_.dropWhile

사용법 : _.dropWhile(array, [predicate=_.identity])
용도 : 조건이 falsey값을 반환할 때까지 앞에서부터 제거

_.fill

사용법 : _.fill(array, value, [start=0], [end=array.length])
용도 :  배열에 특정값을 채움

_.findIndex

사용법 : _.findIndex(array, [predicate=_.identity], [fromIndex=0])
용도 : 객체 배열에서 특정 조건에 해당하는 첫번째 객체의 인덱스를 찾음

_.findLastIndex

사용법 :_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])
용도 :  객체 배열에서 특정 조건에 해당하는 마지막 객체의 인덱스를 찾음

_.first -> head

first -> head로 변경

_.flatten

사용법 : _.flatten(array)
용도 : 배열의 차원을 1차원 낮춤

_.flattenDeep

사용법 : _.flattenDeep(array)
용도 : 배열의 차원을 없앰

_.flattenDepth

사용법 : _.flattenDepth(array, [depth=1])
용도 :  depth만큼의 차원을 낮춤

_.fromPairs

사용법 : _.fromPairs(pairs)
용도 : key, value 배열을 객체로 바꿈 

_.head

사용법 : _.head(array)
용도 : 배열의 첫번째 원소를 반환함

_.indexOf

사용법 : _.indexOf(array, value, [fromIndex=0])
용도 : 배열에서 값의 인덱스 찾기

_.initial

사용법 : _.initial(array)
용도 : 배열의 마지막 원소를 제외한 모든 원소 추출

_.intersection

사용법 : _.intersection([arrays])
용도 : 배열 리스트 중 첫번째 배열과 나머지 배열들의 교집합 원소 추출

_.intersectionBy

사용법 : _.intersectionBy([arrays], [iteratee=_.identity])
용도 : _.intersection + iteratee

_.intersectionWith

사용법 : _.intersectionWith([arrays], [comparator])
용도 : _.intersection + comparator

_.join

사용법 : _.join(array, [separator=','])
용도 : 배열을 구분자를 사이에 두고 연결함

_.last

사용법 : _.last(array)
용도 : 배열의 마지막 원소를 찾음

_.lastIndexOf

사용법 : _.lastIndexOf(array, value, [fromIndex=array.length-1])
용도 :  _.indexOf + 오른쪽을 기준으로 왼쪽으로 검색

_.nth

사용법 : _.nth(array, [n=0])
용도 : 배열에서 n번째 요소 찾음

_.pull

사용법 : _.pull(array, values)
용도 : 배열에서 values에 포함된 값 제거

_.pullAll

사용법 : _.pullAll(array, [values])
용도 : _.pull + 제거할 값이 배열로 입력

_.pullAllBy

사용법 : _.pullAllBy(array, values, [iteratee=_.identity])
용도  : _.pullAll + iteratee

_.pullAllWith

사용법 : _.pullAllWith(array, values, [comparator])
용도 : _.pullAll + comparator

_.pullAt

사용법 : _.pullAt(array, [indexes])
용도 : index의 값을 제거하고, 제거한 index의 배열을 리턴함

_.remove

사용법 : _.remove(array, [predicate=_.identity])
용도 : predicate 조건으로 배열에서 원소를 제거

_.reverse

사용법 : _.reverse(array)
용도 : 배열을 원소 순서를 뒤집는다.

_.slice

사용법 : _.slice(array, [start=0], [end=array.length])
용도 : start ~ end-1 까지의 배열을 만든다.

_.sortedIndex

사용법 : _.sortedIndex(array, value)
용도 : 정렬을 유지한 상태로 삽입되기 위한 index를 찾는다. 

_.sortedIndexBy

사용법 : _.sortedIndexBy(array, value, [iteratee=_.identity])
용도 : _.sortedIndex + iteratee

_.sortedIndexOf

사용법 : _.sortedIndexOf(array, value)
용도 : _.indexOf + 정렬된 배열에서의 value index찾기

_.sortedLastIndex

사용법 : _.sortedLastIndex(array, value)
용도 : _.indexOf + 배열의 정렬 상태 유지하면서 삽입하기 위한 마지막 index

_.sortedLastIndexBy

사용법 : _.sortedLastIndexBy(array, value, [iteratee=_.identity])
용도 : .sortedLastIndex + iteratee

_.sortedLastIndexOf

사용법 : _.sortedLastIndexOf(array, value)
용도 : _.lastIndexOf + 배열의 정렬 상태 유지하면서 삽입하기 위한 마지막 index

_.sortedUniq

사용법 : _.sortedUniq(array)
용도 : _.uniq + 정렬

_.sortedUniqBy

사용법 : _.sortedUniqBy(array, [iteratee])
용도 : _.uniqBy + iteratee

_.tail

사용법 : _.tail(array)
용도 : 배열에서 첫번째 원소 제외한 나머지

_.take

사용법 : _.take(array, [n=1])
용도 : n크기 만큼의 배열만 선택

_.takeRight

사용법 : _.takeRight(array, [n=1])
용도 : 오른쪽에서 n크기 만큼의 배열만 선택

_.takeRightWhile

사용법 : _.takeRightWhile(array, [predicate=_.identity])
용도 : 오른쪽에서 predicate가 false를 반환할 때 까지의 배열 선택

_.takeWhile

사용법 : _.takeWhile(array, [predicate=_.identity])
용도 : 왼쪽에서 predicate가 false를 반환할 때 까지의 배열 선택

_.union

사용법 : _.union([arrays])
용도 : 중복 제외 배열 합치기

_.unionBy

사용법 : _.unionBy([arrays], [iteratee=_.identity])
용도 : _.union + iteratee

_.unionWith

사용법 : _.unionWith([arrays], [comparator])
용도 : _.unio + comparator

_.uniq

사용법 : _.uniq(array)
용도 : 중복제거

_.uniqBy

사용법 : _.uniqBy(array, [iteratee=_.identity])
용도 : _.uniq + iteratee

_.uniqWith

사용법 : _.uniqWith(array, [comparator])
용도 : _.uniq + comparator

_.unzip

사용법 : _.unzip(array)
용도 : 그룹화된 배열을 개별화

_.unzipWith

사용법 : _.unzipWith(array, [iteratee=_.identity])
용도 : _unzip + iteratee

_.without

사용법 : _.without(array, [values])
용도 : 배열에서 값 제거

_.xor

사용법 : _.xor([arrays])
용도 : 서로 다른 값으로 배열 제거

_.xorBy

사용법 : _.xorBy([arrays], [iteratee=_.identity])
용도 :  _.xor + iteratee

_.xorWith

사용법 : _.xorWith([arrays], [comparator])
용도 : _.xor + comparator

_.zip

사용법 : _.zip([arrays])
용도 : 배열을 그룹핑

_.zipObject

사용법 : _.zipObject([props=[]], [values=[]])
용도 : 배열을 key + value 객체로 그룹핑

_.zipObjectDeep

사용법 : _.zipObjectDeep([props=[]], [values=[]])
용도 : _.zipObject + 문자열에 속성 path를 허용

_.zipWith

사용법 : _.zipWith([arrays], [iteratee=_.identity])
용도 : _.zip + iteratee

'공식메뉴얼 > lodash' 카테고리의 다른 글

Collection  (0) 2020.07.12
Lodash란?  (1) 2020.06.27

Lodash란 js 라이브러리 공식 메뉴얼을 학습해보고자 한다.

"A modern JavaScript utility library delivering modularity, performance & extras" 

라고 공식 홈페이지에서 소개하고 있다.
jquery처럼 전역으로 선언해놓고 사용하면 유용하다. 특히 json으로 이루어진 배열을 다룰 때 또는 중첩 구조로 인해 객체 구조가 복잡해졌을 때 사용하면 유용하다.
유사한 라이브러리로는 underscore(https://underscorejs.org/)가 있으나, lodash가 브라우저 변화에 더 안정적이고, 더 많은 API와 성능 향상을 제공한다고 한다.
(참조 : https://benmccormick.org/2014/11/12/underscore-vs-lodash)

아래에 링크에 들어가면 메뉴얼이 잘 정리되어있으나, 학습을 위해 하나하나 뜯어보면서 기록해보기로 한다.

https://lodash.com/

 

Lodash

_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn

lodash.com

제공하는 카테고리 ? 

  • Array
  • Collection
  • Date
  • Function
  • Lang
  • Math
  • Number
  • Object
  • Seq
  • String
  • Util
  • Properties
  • methods

'공식메뉴얼 > lodash' 카테고리의 다른 글

Collection  (0) 2020.07.12
Array  (0) 2020.06.27

1. General configuration

  • 기본적으로 development profile을 사용한다. 

2. Running the Java server

  • 기본 서버주소 :  http://localhost:8080
  • hot reload가 활성화 되어있음.
  • Maven 이용시
    - maven wrapper를 제공하므로 따로 메이븐 설치가 필요없음.
    - ./mvnw(mac, linux),  mvnw(window)로 어플리케이션 실행. 
    (기본 maven task인 spring-boot:run 을 실행한다.)
    - live reload 사용시 ./mvnw -P-webpack를 통해서 webpack task를 제외시킬 수 있다. 
  • Gradle 이용시
    - gradle wrapper를 제공하므로 따로 그레이들 설치가 필요없음.
    - ./gradlew(mac, linux),  gradlew(window)로 어플리케이션 실행. 
    (기본 gradle task인 bootRun을 실행한다.)
    - live reload 사용시 ./gradlew -x webpack를 통해서 webpack task를 제외시킬 수 있다. 

3. Working with Angular/React

  • npm start 또는 yarn start 로 webpack을 실행시킬 수 있다. (pacage.json scripts참조)
  • webpack hot module reload 서버는 http://localhost:9060/ 로 접근. 
    (Java back-end에 접근하기 위한 proxy 주소 http://127.0.0.1:8080/api)
  • BrowserSync task는 http://localhost:9000/ 을 통해 확인. 
    (http://localhost:9060/ (the Webpack “hot module reload” server)를 프록시 서버로 함.) and which will synchronize the 
  • BrowserSync UI는 http://localhost:3001/ 을 통해 확인.
  • Other NPM/Yarn tasks
    - npm run lint : TypeScript 코드 스타일 검사.
    - npm run lint:fix : TypeScript 스타일을 자동 수정.
    - npm run tsc : TypeScript 코드 컴파일
    - npm run test : Jest 단위 테스트 실행
    -
    npm run test:watch : Jest 단위 테스트를 실행, 코드가 변경되면 자동 피드백.
    - npm run e2e : “end to end” 테스트를 실행(Protractor가 설치됐을 시만 작동)

4. Using a database

  • H2 database
    - http://localhost:8080/h2-console를 통해 접속
  • Database updates
    - JPA entity를 수정하면 db스키마를 따로 수정해줘야 한다.
    (DB 변경 내역 관리를 위해 JPA generator가 아닌, liquibase를 이용함.)
    -
    /src/main/resources/config/liquibase/ 폴더에서 liquibase 관련 내용 확인 가능.
  • entity sub-generator를 통한 db업데이트
    - entity sub-generator를 이용하면 change log가 자동 등록됨.
  • liquibase:diff goal를 통한 db업데이트
    1. JPA entity를 수정
    2. Complie application (Java code를 기반으로 task가 작동하므로 반드시 컴파일이 필요)
    3. /mvnw liquibase:diff (또는 ./mvnw compile liquibase:diff (컴파일후))
    (./gradlew liquibaseDiffChangelog -PrunList=diffLog)
    4. src/main/resources/config/liquibase/changelog 의 체인지 로그 확인.
    5. src/main/resources/config/liquibase/master.xml에 추가
  • change log 편집을 통한 업데이트
    1. JPA entity를 수정
    2. src/main/resources/config/liquibase/changelogd에 change log 생성
    (로그 생성일을 yyyyMMddHHmmss_내용 포맷으로 접두어 붙이는게 네이밍 룰)
    3. src/main/resources/config/liquibase/master.xml에 추가

 

참조 : https://www.jhipster.tech/development/

 

Using JHipster in development

Using JHipster in development Please check our video tutorial on creating a new JHipster application! Summary General configuration Running the Java server Working with Angular/React Using a database Internationalization General configuration IDE configura

www.jhipster.tech

 

JHipster에서 컨트롤러를 생성하길 원할 경우

  • jhipster spring-controller <entity-name>
  • Swagger : 개발환경에서 Administration > API 에서 등록된 컨트롤러를 확인할 수 있다.
  • @Secured 어노테이션을 권한 옵션과 함께 클래스 또는 메소드에 붙임으로써 접근 제한을 할 수 있다.

JHipster에서 서비스를 생성하길 원할 경우

  • JHipster spring-service <entity-name>
  • JHipster는 entity 생성시 Service계층을 따로 생성하지 않는 이유는?
    - 기본적인 CRUD를 제공하는데 목적이 있으므로 서비스 계층이 불필요하다고 생각.
    - 서비스 계층이 여러 repository를 동시에 사용하므로, entity 생성기와 개념이 맞지 않다고 생각.
    + AOP(Proxy)를 위한 interface또한 service 계층에서 불필요하다 생각.
  • 컨트롤러 마찬가지로 @Secured어노테이션을 통한 보안 옵션 사용 가능.

 

참조 : 

- https://www.jhipster.tech/creating-a-spring-controller/

- https://www.jhipster.tech/creating-a-spring-service

 

Creating a service

Creating a Spring service Introduction Note: this sub-generator is much simpler than the entity sub-generator that creates full CRUD entities This sub-generator generates a Spring Service bean, which is where your application’s business logic is supposed t

www.jhipster.tech

 

Creating a controller

Creating a Spring controller Introduction Note: this sub-generator is much simpler than the entity sub-generator that creates full CRUD entities This sub-generator generates a Spring MVC REST Controller. It is also able to create REST methods. In order to

www.jhipster.tech

 

JHipster에서 엔티티 생성시 일반적으로 다음과 같은 요소들이 필요하다.

  • A database table
  • A Liquibase change set
  • A JPA Entity
  • A Spring Data JPA Repository
  • A Spring MVC REST Controller, which has the basic CRUD operations
  • An Angular router, a component and a service
  • An HTML view
  • Integration tests, to validate everything works as expected
  • Performance tests, to see if everything works smoothly

엔티티 간 관계가 필요할 시 추가적으로

  • A database foreign key
  • Specific JavaScript and HTML code for managing this relationship

JHipster가 제공하는 entity sub-generator를 이용하면 위의 요소들을 자동생성 해준다.

  •  jhipster entity <entityName> --[options] 

sub-generator에서 사용 가능한 옵션은 jhipster entity --help를 통해 확인해볼 수 있다.

  • --table-name <table_name> : entity와 다른 이름으로 테이블을 생성하고 싶을 시. (기본 옵션은 엔티티와 동일한 이름으로 테이블을 생성한다.)
  • --angular-suffix <suffix> : 모든 angular router에 접미사를 추가하고 싶을 시.
  • --client-root-folder <folder-name> : client side 엔티티들의 루트 폴더 이름 설정.
  • --regenerate : entity 재생성.
  • --skip-server : client-side 코드만 생성.
  • --skip-client : server-side 코드만 생성.
  • --skip-db-changelog : Liquibase 에서 change log 생성을 생략.
  • --db : server-side를 생략할 때 db

 

JHipster UML and JDL Studio를 통한 다중 엔티티 생성

(JHipster UML, JDL Studio)

  • jhipster import-jdl your-jdl-file.jh.
  • jhipster import-jdl ./my-jdl-file.jdl --json-only : .jhipster 폴더에 존재하는 json 파일만 엔티티 생성.
  • jhipster import-jdl ./my-jdl-file.jdl --force : import-jdl 옵션은 기본적으로 변경된 엔티티만 재생성함. --force 옵션을 통해 모든 엔티티 재성성.

엔티티 생성시 정보

  • Entity fields
    - java나 사용하는 db의 예약어들은 field keyword로 사용할 수 없다. 
  • Field types
    - java타입을 기본적으로 사용하고, db종류에 따라 키워드가 변경된다.
  • Validation
    - 각각의 필드에 유효성 룰을 추가할 수 있고, 이는 client-side, server-side에 각각 추가 된다.
    (Angular, React, Vue validation / Java Domin object bean validation)
  • Entity relationships
    - 엔티티 간 관계 설정
  • Generating a separate service class for your business logic
    - 서비스 계층 생성 여부
  • Data Transfer Objects (DTOs)
    - 서비스 계층 생성 시 DTO 사용 여부를 선택할 수 있다.
  • Filtering
    - JPA를 통한 필터링 옵션을 제공한다.
  • Pagination
    - 페이지네이션은 Link header를 이용한다.
    - No pagination(back-end가 페이징 처리되지 않음), pagination(Bootstrap pagination component), Infinite scroll(directive 사용) 3가지 옵션을 제공한다. 

엔티티 업데이트

- sub-generator에 이미 생성 된 엔티티의 이름을 재입력할 경우  엔티티 업데이트가 가능하다. (.jhipster 디렉토리에 .json파일 참조)

- 재생성 / 필드, 관계 추가 / 필드, 관계 제거 등의 옵션 선택이 가능한다.

 

 

참조 : https://www.jhipster.tech/creating-an-entity/

command line에서 jhipster generator를 통한 어플리케이션 생성 시 옵션을 줄 수 있다.

(옵션 보기 : jhipster app --help)

 

  • --help : 옵션 보기
  • --blueprint : - 사용할 블루 프린트 설정 ex> jhipster --blueprint kotlin
  • --skip-cache : Do not remember prompt answers (Default: false)
  • --skip-git : git에 자동 등록하지 않기.
  • --skip-install : 의존성 자동 설치 하지 않기.
  • --skip-client : server-side 어플리케이션만 생성.
  • --skip-server : client-side 어플리케이션만 생성.
  • --skip-user-management : 사용자 관리 생략. 
  • --i18n : client-side 생략시 다국어 생략.
  • --auth : server-side 생략시 인증 타입 선택.
  • --db : server-side 생략시 DB타입 선택
  • --with-entities : .jhipster폴더에 있는 엔티티 설정 정보로 엔티티 재생성.
  • --skip-checks : 필요 도구 확인 생략.
  • --jhi-prefix : services, components, state/route이름 접두어 설정. (기본 : jhi)
  • --entity-suffix : 엔티티 class이름 접미어 설정. (기본 : x)
  • --dto-suffix : DTO의 접미어 설정. (기본 : DTO)
  • --yarn : NPM 대신 Yarn을 기본 설정으로 사용.
  • --prettier-java : Java 클래스 포멧에 prettier-java을 사용.
  • --experimental
  • --skip-fake-data : liquibase fake data 생성 생략.
  • --creation-timestamp

--force를 추가시 기존에 존재하는 파일들을 덮어쓰기한다.

엔티티를 포함해서 모든 어플리케이션 재성성시 : jhipster --force --with-entities

 

참조 : https://www.jhipster.tech/creating-an-app/

일전의 환경 설정과 로컬 jhipster-generator가 설치되어있다는 가정

(npm -g generator-jhipster *이전의 jhipster설치 글 참조)

터미널에서 폴더를 생성한 후 해당 폴더로 이동.

  • jhipster 입력 후 커맨드에 나오는 질의에 원하는 어플리케이션의 형태에 따라 옵션을 선택
  • 어플리케이션 생성 완료 후 해당 폴더에서 ./mvnw 또는 ./gradlew 입력시 개발(-Pdev) 환경 어플리케이션을 실행하게 된다.(http://localhost:8080 에서 이용)
  • JavaScript/TypeScript live reload를 원할 시 npm start 또는 yarn start를 실행한다.
    (live reload 이용시 ./mvnw -P-webpack or ./gradlew -x webpack를 이용. webpack 관련 설정을 제외, 서버 실행 속도를 높일 수 있다.)

어플리케이션 옵션

1. Which type of application would you like to create?

Monolithic이 가장 대중적인 형태

  • Monolithic application
  • Microservice application
  • Microservice gateway
  • JHipster UAA serve

2. What is the base name of your application?

  • 만들 어플리케이션 이름 입력

3. What is your default Java package name?

  • 자바 패키지 계층 설정

4. Do you want to use the JHipster Registry to configure, monitor and scale your application?

  • 마이크로서비스 형태 선택시 필수 선택

5. Which typeof authentication would you like to use?

원하는 인증 타입을 선택

  • JWT authentication
  • OAuth 2.0 / OIDC Authentication
  • HTTP Session Authentication
  • Authentication with JHipster UAA server

6. Which type of database would you like to use?

원하는 데이터베이스 형태 (RDBMS?NO-SQL? 를 결정)

  • An SQL database (H2, MySQL, MariaDB, PostgreSQL, MSSQL, Oracle), which you will access with Spring Data JPA
  • MongoDB
  • Cassandra
  • Couchbase
  • Neo4j
  • No database (only available when using a microservice application with JWT authentication)

7. Which production database would you like to use?

  • 배포환경에서 사용할 db(src/main/resources/config/application-prod.yml에서 확인)

8. Which development database would you like to use?

개발환경에서의 db (src/main/resources/config/application-dev.yml에서 확인)

  • H2, running in-memory.
    • 서버 재시작시 data 초기화됨
  • H2, with its data stored on disk.
    • 파일 형태로 로컬 pc에 저장(*권장)
  • The same database as the one you chose for production
    • 배포환경과 동일한 환경으로 db를 이용하나 설정이 복잡 (도커 사용)

9. Do you want to use the Spring cache abstraction?

스프링 캐쉬를 사용할 지, 성능상의 이슈에 따라 결정

10. Do you want to use Hibernate 2nd level cache?

  • SQL DB 선택시만 사용 가능(Jhipster가 JPA를 사용하기 때문)

11. Would you like to use Maven or Gradle?

빌드 툴 택 1

  • maven
  • gradle

12. Which other technologies would you like to use?

  • API first development using swagger-codegen
  • Search engine using ElasticSearch
  • Clustered HTTP sessions using Hazelcast
  • WebSockets using Spring Websocket
  • Asynchronous messages using Apache Kafka

13. Which Framework would you like to use for the client?

  • Angular
  • React
  • VueJs (* jhipster에서 제공하는 뷰 템플릿 관련 공식 라이브러리 추가 설치 필요)
      ([https://github.com/jhipster/jhipster-vuejs](https://github.com/jhipster/jhipster-vuejs))

14. Would you like to use a Bootswatch theme?

부트스트랩 테마 결정

15. Would you like to use the Sass stylesheet preprocessor for your CSS?

프론트엔드 빌드시 Sass 전처리기를 사용할지 여부

16. Would you like to enable internationalization support?

다국어 사용 여부

17. Which testing frameworks would you like to use?

기본으로 Spring-Junit, JavaScript-Jest을 제공함.

  • Performance tests using Gatling
  • Behaviour tests using Cucumber
  • Angular integration tests with Protractor

18. Would you like to install other generators from the JHipster Marketplace?

출처 : https://www.jhipster.tech/creating-an-app/

jhipster는 docker를 통해 개발과 배포에 있어서 편리함을 제공한다.

docker를 이용하면?

  • 배포 환경과 동일한 환경에서 개발이 가능하다.
  • 인프라 확장이 용이하다. (docker-compose scale)

1. 환경

jhipster가 제공하는 도커 환경을 이용하기 위해 도커와 도커 컴포즈 설치가 선행되어야 한다.

2. 도커 이미지 만들기

java애플리케이션을 도커 이미지로 만들기 위해 Jib(https://github.com/GoogleContainerTools/jib) 라이브러리를 이용한다.

2.1 로컬에 설치된 도커데몬을 이용

  • With Maven, type: ./mvnw package -Pprod verify jib:dockerBuild
  • With Gradle, type: ./gradlew -Pprod bootJar jibDockerBuild

2.2 로컬에 도커 설치 없이 빌드 후 도커 레지스트리 배포

  • With Maven, type: ./mvnw package -Pprod verify jib:build
  • With Gradle, type:./gradlew -Pprod bootJar jib

2.3 오프라인 환경에서 이용

  • jib은 docker registry에서 최신 버전의 이미지를 받아오는게 우선적이므로, 인터넷이 불가능한 환경이라면 아래와 같이 이용.
    (cache에 저장된 이미지를 사용 )

  • With Maven, type : ./mvnw -Pprod package verify jib:dockerBuild --offlineWith

  • Gradle, type : ./gradlew -Pprod bootJar jibDockerBuild --offline

2.4 기타

docker-compose -f src/main/docker/app.yml up 시 기타 필요한 환경 컨테이너를 함께 띄운다.

만약, 각각의 따로 띄우거나 컨트롤 하고 싶다면 src/main/docker의 *.yml 파일을 참조하여 이용하면 된다.

  • PostgreSQL : docker-compose -f src/main/docker/postgresql.yml up,
  • Elasticsearch : docker-compose -f src/main/docker/elasticsearch.yml up
  • Sonar : docker-compose -f src/main/docker/sonar.yml up

3. 도커이미지 띄우기

2.번에서 빌드한 도커 이미지를 가동시키기 위한 cmd

  • docker-compose -f src/main/docker/app.yml up
    (db, search engine, registry 등 연관 이미지를 함께 가동시킴)
  • 도커 *.yml 위치 : src/main/docker

4. 도커 커맨드

  • 모든 컨테이너 확인
    - docker container ps -a
  • 컨테이너 상태 확인(cpu, menory등의 관련 정보)
    - docker container stats
  • 컨테이너 스케일 조정
    - docker-compose scale test-app=4("test"어플리케이션의 인스턴스를 4개로 조정)
  • 컨테이너 멈추기
    - docker-compose -f src/main/docker/app.yml stop
    - docker container stop <container_id>
  • 컨테이너 삭제**
    - docker container rm <container_id>**

출처 : https://www.jhipster.tech/docker-compose/

+ Recent posts