Skip to content

Instantly share code, notes, and snippets.

@namkyu
Last active May 8, 2018 01:06
Show Gist options
  • Save namkyu/87cb428d7d06b65804015781a7ad115e to your computer and use it in GitHub Desktop.
Save namkyu/87cb428d7d06b65804015781a7ad115e to your computer and use it in GitHub Desktop.
spring boot 2.0 정리 #spring_boot

시작하기

maven은 pom 파일을 상속받는다.
<parent> 안에 부모를 선언한다.
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.0.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>
스프링 부트 pom.xml 파일의 dependency에 버전을 명시하지 않는 이유는 부모 pom에 버전이 명시되어 있기 때문이다. (의존성 버전 명시 안하는 것은 어마어마하게 편해진 것이다.)
애플리케이션 pom -> spring-boot-starter-parent pom -> spring-boot-dependencies pom 파일에 버전 들어가 있음

spring-boot-starter 라이브러리가 굉장히 많음
https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-starter

RC2 버전은 milestones 리포지토리(사설)에 있기 때문에 repository 설정이 추가되어야 한다.
스냅샷(daily빌드), M버전(몇달주기), RC버전(M버전이좀정리되면)
GA버전은 최정 릴리즈 버전이다.
GA버전은 중앙 메이븐 저장소에 올라간다.

@RestController, @RequestMapping은 스프링 MVC 애노테이션이다.

@EnableAutoConfiguration
자동 설정 기능
어떤 의존성이 classpath에 있느냐에 따라 동작한다.

org.springframework.boot.loader.jar.JarFile 이놈이 nested jar파일을 읽어온다. jar 파일을 unpack 할 필요가 없다.

내가 개발하는 애플리케이션에서 의존성의 버전을 변경할 수 있다.
maven properties 를 override 할 수 있다.
<common-lang3.version>3.7</common-lang3.version>

maven에서 <optional>true</optional> 의미
B프로젝트에 optional 설정이 있다고 하자
A프로젝트가 B프로젝트를 의존하게 된다면 optional이 걸려 있는 dependency는 가져오지 않는다.

src/main/java 디렉토리 안에 A.java 파일을 생성해서 사용하는 것을 default 패키지를 사용한다라고 말한다.

root package와 default package는 다르다.

@SpringBootApplication 안에 componentScan이 존재하는 이유는 스캔을 통해 빈들을 등록하기 위함이다
bean외에도 configuration설정 또한 탐색해서 등록하게 된다.
즉, 다음과 같이 비교할 수 있겠다.
DemoApplication.java == applicationContext.xml
@ComponentScan == <componentscan></componentscan>

devtools

intelliJ는 코드를 수정한다고 해서 바로 적용되는 것이 아니다. Build Project를 한번씩 눌러줘야 변경사항이 반영된다. classpath에 변경된 파일을 적용하는 시점이 Build Project를 할 때인가 보다.
Eclipse는 저장할 때마다 classpath에 반영한다.

devtools 동작 방법
java 코드 수정 후 Build Project하면 app이 restart된다. 
내가 개발하는 class 파일만 재로딩하기 때문에 톰캣을 껐다 키는 것 보다 훨씬 빠르다.
jrebel은 bytecode를 교체하는 방법

배너, SpringApplication

이미지도 배너로 만들 수 있다.

의존성을 가져오는 저장소와 플러그인을 가져오는 저장소 2가지가 있다.

스프링 부트 이전에서는 계층 구조로 설계를 했었다. parent, child
예전에 applicationContext.xml, dispatcherServelt.xml 과 같이 두 개의 애플리케이션으로 분리하고 web --> root를 바라보는 형식으로 설계했다.

SpringApplication 커스터마이징, Admin 기능

스프링5에서는 web이 두 가지로 분류된다. (servlet, reactice web)

MBean (Managed Beans)
- JMX(Java Management Extension) 기술을 이용하여 J2EE 서버의 상태를 조정, 제어할 수 있도록 해주는 JavaBean 오브젝트이다.
spring.application.admin.enabled=true 설정하고 boot 실행
jconsole.exe 실행하여 접속할 수 있음
메모리 누수 판단 조건 : Heap Memory Usage 를 보면 메모리가 올라가다가 가비지가 발생하면 뚝 떨어져야 한다. 잘 안 떨어지면 누수가 있다는 것이다.

프로퍼트, 각종 외부 설정의 우선 순위

-Dname=nklee 로 시작하는 것은 시스템 프로퍼티
springboot.jar --name=nklee 는 애플리케이션 프로퍼티

1. 애플리케이션 프로퍼티 program arguments
2. 시스템 프로퍼티 VM option
3. application-{profile}.properties

application-{profile}.properties 파일이 존재하지 않으면 application-default.properties 파일이 로드된다.

YAML 사용

yml 파일이 properties 로 변환된 후 environment 에 추가된다.
모든 properties 파일은 spring environment 객체에 추가되고 @Value("${root.prop}") 와 같이 참조가 가능하다.
@PropertySource 는 properties 파일만 지원한다. yml 파일은 읽지 못함

다음과 같은 형태의 properties 값은 @Value("${mypojo.list}") 와 같이 사용할 수 없다.
mypojo:
  list:
  -
    name: my name
    descr: my description
  -
    name: another name
    descr: another description
  -
    name: another name
    descr: another description

다음과 같이 사용해야 한다.
@Component
@ConfigurationProperties(prefix="mypojo")
public class MyPojos {

    private List<MyPojo> list;

    public List<MyPojo> getList() {
        return list;
    }

    public void setList(List<MyPojo> list) {
        this.list = list;
    }
}

ConfigurationProperties 장점, 단점

다음과 같이 Validated 추가 가능
@Component
@ConfigurationProperties(prefix="mypojo")
@Validated
public class MyPojos {

    @NotNull
    private List<MyPojo> list;

spring 프로파일, 기본 로깅

spring.profile.active 가 dev인 경우 다음의 빈이 생성된다.
@Component
@Profile("dev")
public class DevBean {
}

ConfigurableEnvironment 이용해서 프로그램적으로 profile.active를 셋팅할 수 있다.

commons logging을 래퍼로 쓰고 logback이 구현체로 기본 제공된다.
SpringApplication소스를 보면 import org.apache.commons.logging.Log; 를 사용하고 있다.

application.yml 에서 debug: true 로 주면 로깅 레벨이 DEBUG 모드로 활성화되는 것이 아니고 spring boot, jpa 등의 로그를 상세하게 출력한다.
java -jar app.jar --debug 이것도 상세 로그 출력하는 옵션이다.

spring.output.ansi.enabled: always 주면 console에 컬러가 출력된다.

trace는 완전 빡세게
debug는 빡세게 로그를 찍는다.

logging.path: ./logs/ 로 지정해서 사용하고 싶으면 logging.file: my.log 를 제거해야 한다.
logging.file: ./logs/my.log 이렇게 설정하니 내가 원하는 디렉토리에 원하는 파일명으로 생성된다.

logback-spring.xml 이름을 권자 (-spring 붙여서)

로그 파일 규칙을 만들어서 관리하는 것이 좋음

클래스 패스에 logback-spring.xml 추가하니 application.yml 안에 설정한 로깅 설정이 무시된다.

logback.xml : 스프링이 로딩되기 전에 초기화
logback-spring.xml : 스프링이 로딩된 후 초기화, auto scanning configuration은 동작하지 않는다.
<springProfile name="dev"> 와 같은 설정을 사용하고 싶다면 logback-spring.xml 로 생성하라.

logback-spring.xml 파일 안에서 다음과 같이 사용 가능하다. Environment 키, value를 참조할 수 있음
<springProperty scope="context" name="myName" source="my.name" defaultValue="nklee"></springProperty>

웹 애플리케이션, HttpMessageConverters

기본 컨버터에 추가적으로 컨버터를 등록하기 위해서는 다음과 같이 추가한다.
@Bean
public HttpMessageConverters customConverter() {
    GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
    return new HttpMessageConverters(gsonHttpMessageConverter);
}

기본적으로 등록되어 있는 컨버터
컨버터 : class org.springframework.http.converter.ByteArrayHttpMessageConverter
컨버터 : class org.springframework.http.converter.StringHttpMessageConverter
컨버터 : class org.springframework.http.converter.StringHttpMessageConverter
컨버터 : class org.springframework.http.converter.ResourceHttpMessageConverter
컨버터 : class org.springframework.http.converter.ResourceRegionHttpMessageConverter
컨버터 : class org.springframework.http.converter.xml.SourceHttpMessageConverter
컨버터 : class org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
컨버터 : class org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
컨버터 : class org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
컨버터 : class org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter

@RequestBody를 쓰면 메세지 컨버터를 사용해서 처리된다.


spring.mvc.static-path-pattern: /static 를 추가하면

WebJar 그리고 컨텐츠 협상

프론트엔드 스크립트를 jar 형태로 제공해 준다.
<script>는 끝나는 body 바로 위에넣어둬야 랜더링이 빠르다.
컨텐츠 캐쉬를 주려면 옵션을 추가해 줘야 한다.

받고자 하는 리소스를 요청의 확장자를 이용하지 말아라. ex) /test.json
Accept header를 이용하거나 test?format=json 와 같이 사용해라.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment