Skip to content

Instantly share code, notes, and snippets.

@ihoneymon
Last active April 21, 2020 04:51
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save ihoneymon/a343e2f4a0299988206e to your computer and use it in GitHub Desktop.
Save ihoneymon/a343e2f4a0299988206e to your computer and use it in GitHub Desktop.
스프링부트springboot 이야기

1-1 스프링부트springboot 이야기

1. 스프링부트springboot란?

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.

  • 스프링부트는 단독실행되는, 실행하기만 하면 되는 상용화 가능한 수준의 스프링 기반 애플리케이션을, 쉽게 만들어낼 수 있다.
  • 최소한의 설정으로 스프링 플랫폼과 서드파티 라이브러리들을 사용할 수 있도록 하고 있다.

1.1. 스프링부트 기능

  • Create stand-alone Spring applications

단독실행가능한 스프링애플리케이션을 생성한다.

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

내장형 톰캣, 제티 혹은 언더토우를 내장(WAR 파일로 배포할 경우에는 필요없음)

  • Provide opinionated 'starter' component to simplify your build configuration

기본설정되어 있는 'starter' 컴포넌트들을 쉽게 추가

  • 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

설정을 위한 XML 코드를 생성하거나 요구하지 않음

1.2. 스프링부트 자동설정 - autoconfigure

  • web을 기본선택한 프로젝트 생성
    • Application.java 확인

      • @SpringBootApplication 확인
      @Target(ElementType.TYPE)
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      @Inherited
      @Configuration // JavaConfig
      @EnableAutoConfiguration // 자동설정 활성화
      @ComponentScan // 해당위치부터 컴포넌트 스캔 진행
      public @interface SpringBootApplication {
      
      	/**
      	 * Exclude specific auto-configuration classes such that they will never be applied.
      	 * @return the classes to exclude
      	 */
      	Class<?>[] exclude() default {};
      
      }
      
    • autoconfig 패키지 확인

    @Conditional, @ConditionalOnBean, @ConditionalOnMissingBean, @ConditionalOnClass

1.3. 의존성 라이브러리 추가

1.3.1. starter POMs

  • 사전에 정의된 컴포넌트와 그와 관련된 의존성 라이브러리들에 대한 정의를 가지고 있음
  • 선언되어 호출되는 순간, 빌드프로그램(메이븐, 그레들)에 의해서 의존성이 추가된다.
  • 사용을 위해서는 인터넷이 연결되어 있어야 한다.
    • 인트라넷 환경에서 사용하기 위해서는 Nexus Repository가 구성되어 있어야 한다.
  • starter POMs sample
    • build.gradle - spring-boot-starter-data-jpa starter
    • spring.provides: 스프링부트에 추가되는 컴포넌트 정의
    provides: spring-orm,hibernate-entity-manager,spring-data-jpa
    

1.3.2. h2database

  • 참고: h2datbase
  • 스프링부트에서 사용하는 컴포넌트는 스프링부트의 버전에 따라 사전정의된 버전을 따른다.
  • h2database는 경량 데이터베이스 엔진이다.
    • 로컬, 테스트용으로 사용
    • MySQL, Oracle 모드 지원하기 때문에 운영모드가 전환시에도 별다른 무리가 없다.
  • 추후 Profiles 관련하여 개발방법 소개예정
  • 로컬에서 DB를 사용하기 위해서 MySQL, Oracle DB서버 설치 부담감소

1.3.3. spring-boot-starter-data-jpa

  • 참고: Spring Data JPA 번역 - 아라한사
  • Spring Data JPA와 관련된 라이브러리(spring-orm,hibernate-entity-manager,spring-data-jpa)을 포함하고 있다.
  • @EntityRepository 기본사용

1.3.4. 패키지 구성: 기능Feautre? 계층Layer?

  • 단일 서비스 혹은 컴포넌트의 경우에는 계층으로 구분지어도 무난하다고 생각하지만...

2. 스프링부트 기본구조

2.1. 프로젝트 디렉토리 구조

  • 전형적인 프로젝트 계층구조를 가지고 있다.
디렉토리 의미
src/main/java Production Java source
src/main/resources Production resources
src/test/java Test Java source
src/test/resources Test resources

2.1. @SpringBootApplication 선언된 클래스는 패키지 최상위에 위치한다.

  • 참고: Locating the main application class
  • 앞에서 살펴봤던 @ComponentScan 가 제대로 동작하려면 스프링부트애플리케이션클래스는 패키지 상단에 위치한다.
  • 기본적인 구조
com
+- innotree
   +- myproject
       +- Application.java
       |
       +- domain
       |   +- Customer.java
       |   +- CustomerRepository.java
       |
       +- service
       |   +- CustomerService.java
       |
       +- web
           +- CustomerController.java

2.2. 템플릿 엔진

  • 참고: Template engines
  • JSP 보다는 템플릿 엔진의 사용을 권장한다.
  • 기본 디렉토리는 src/main/resources/templates 사용을 권장한다.

2.3. 정적 자원

  • org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration 중에서
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };
  • 위에서 보는 것과 같이 클래스패스classpath 상에서 /META-INF/resources/, /resources, /static, /public 경로를 기본탐색한다.
  • /WEB-INF/resources 의 경우, jar 파일로 배포할 경우에는 인식하지 않기때문에 사용하지 않도록 주의한다.
  • 정적 자원들은 /static 디렉토리 사용을 권장한다.
  • 별도의 루트('/') 경로에 대한 설정이 되어 있지 않은 경우에는 Spring MVC auto-configuration 와 관련된 자동설정에 따라서 static index.html을 지원하게 된다.

2.3.1. bower 사용: 프론트엔드 의존성관리

  • .bowerrc 파일 작성
{
    "directory": "src/main/resources/static/bower_components",
    "json": "bower.json"
}
  • bower.json 파일 작성: bower init 사용
{
  "name": "project-word-management",
  "dependencies": {
    "angular": "~1.4.3",
    "angular-resource": "~1.4.3",
    "bootstrap-css-only": "~3.2.0",
    "requirejs": "~2.1.19"
  },
  "version": "0.0.1",
  "homepage": "https://github.com/ihoneymon/project-word-management",
  "authors": [
    "ihoneymon <ihoneymon@gmail.com>"
  ],
  "description": "프로젝트 용어 관리",
  "moduleType": [
    "amd",
    "globals"
  ],
  "keywords": [
    "springboot",
    "gradle",
    "bower"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "src/main/resources/static/bower_components",
    "test",
    "tests"
  ]
}
  • build.gradle task 정의
task bowerInstall(type:Exec) {
	inputs.files "bower.json"
	commandLine "bower", "install"
}
  • $ gradle bowerInstall 를 프로젝트에서 실행하면 bower.json 에 선언된 의존성항목들이 추가된다.

3. 외부설정

3.1. PropertySource 의 값, 속성 오버라이드 순서

  1. Command line arguments.
  2. JNDI attributes from java:comp/env.
  3. Java System properties (System.getProperties()).
  4. OS environment variables.
  5. A RandomValuePropertySource that only has properties in random.*.
  6. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  7. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  8. Application properties outside of your packaged jar (application.properties and YAML variants).
  9. Application properties packaged inside your jar (application.properties and YAML variants).
  10. @PropertySource annotations on your @Configuration classes.
  11. Default properties (specified using SpringApplication.setDefaultProperties).

3.1.1. 외부설정파일은 기본적으로 /src/main/resources에 위치한다.

  • /src/main/resources/application.properties 혹은 /src/main/resources/application.yml
    • 개인적으로는 YAML을 선호함
    • 추후에 사용할 Profile 기능을 사용시에 application.yml 는 하나의 문서에서 확인가능

3.2. STS의 SpringBoot @ConfigurationProperties 지원


○ 참고문헌

@teddyhong182
Copy link

허니몬님~ 사랑합니다.^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment