스프링 부트 - ing (계속 추가)

공부·2024년 12월 10일

:: 학습 자료

학습 자료 링크


:: DB 설정 (H2)

  • application.properties

  • DATABASE

  • spring.h2.console.enabled=true
  • spring.h2.console.path=/h2-console
  • spring.datasource.url=jdbc:h2:~/local
    • JDBC URL 부분을 변경하고 싶으면 아래와 같이 변경
      • spring.datasource.url=jdbc:h2:./db_dev;MODE=MySQL
      • URL에 맞게 파일도 생성
        • ex) Git Bash에 touch db_dev.mv.db 같은 형식으로 생성 (Mac)
          ex) copy con db_dev.mv.db (Window)
  • spring.datasource.driverClassName=org.h2.Driver
  • spring.datasource.username=sa
  • spring.datasource.password=
  • spring.jpa.hibernate.ddl-auto=update
  • spring.h2.console.enabled: H2 콘솔에 접속할 것인지를 묻는 항목이다. 여기서는 true로 설정한다. H2 콘솔은 H2 데이터베이스를 웹 UI로 보여 준다.
  • spring.h2.console.path: H2 콘솔로 접속하기 위한 URL 경로이다.
  • spring.datasource.url: 데이터베이스에 접속하기 위한 경로이다.
  • spring.datasource.driverClassName: 데이터베이스에 접속할 때 사용하는 드라이버 클래스명이다.
  • spring.datasource.username: 데이터베이스의 사용자명이다(사용자명으로 기본값인 sa로 설정한다.).
  • spring.datasource.password: 데이터베이스의 비밀번호이다(여기서는 로컬에서 개발 용도로만 사용하므로 비밀번호를 설정하지 않고 비워 두었다.).

:: 의존성 (저장)

  • build.gradle

  • implementation 'org.springframework.boot:spring-boot-starter-web'
  • compileOnly 'org.projectlombok:lombok'
  • developmentOnly 'org.springframework.boot:spring-boot-devtools'
  • annotationProcessor 'org.projectlombok:lombok'
  • testImplementation 'org.springframework.boot:spring-boot-starter-test'
  • testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
  • testImplementation 'org.junit.jupiter:junit-jupiter'
  • runtimeOnly 'com.h2database:h2'
  • implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
  • implementation 'org.springframework.boot:spring-boot-starter-jdbc'

:: 스프링 부트 주요 폴더와 파일 설명

  • settings.gradle
    • 프로젝트 설정 파일
  • build.gradle
    • 빌드 설정 파일
    • 의존성 관리
  • src/main/java
    • 자바 소스 파일
  • src/main/resources/static
    • 정적 파일
      • 이미지, 자바스크립트, CSS 등
  • src/main/resources/templates
    • 템플릿 파일
      • HTML 등
  • src/main/resources/application.properties
    • 설정 파일
      • 포트번호, 데이터베이스 설정 등

:: 어노테이션

  • @Controller
    • 컨트롤러 클래스로 만들어준다. (클래스 단에 부착)
      • 컨트롤러(점원)는 서비스(요리사)와 다르게 브라우저(고객)의 요청(GET http://localhost:8080/about)을 받아서 처리하는 역할을 합니다.
  • @GetMapping
    • 컨트롤러 클래스 안에 액션 메서드를 정의할 때 사용합니다.
    • 액션메서드 : 일반 메서드와 다르게 브라우저(고객)가 호출 할 수 있습니다.
  • @ResponseBody
    • 본문에 해당 메서드의 내용 출력
  • @Controller + @ResponseBody = @RestController
  • @Builder
    • 관련 객체에 어노테이션으로 생성 시 메서드 체이닝 방식으로 사용 가능
          public Article getArticle() {
          return Article
                  .builder()
                  .title("제목")
                  .body("내용")
                  .build();
      }
    • 순서에 종속적이지 않기에 순서 상관 없이 선언 가능
  • @Component
    • 클래스에 붙이면 자바 빈에 등록된다.
    • 해당 어노테이션이 명시되어 있으면 Spring이 자동으로 클래스의 인스턴스를 생성
    • @Autowired를 명시하면 필요한 인스턴스를 자동으로 주입
  • @RequiredArgsConstructor (Lombok)
    • 초기화 되지않은 final 필드나, @NonNull 이 붙은 필드에 대해 생성자를 생성
    • 새로운 필드를 추가할 때 다시 생성자를 만들어서 관리해야하는 번거로움을 없애줌
    • 예로 생성자로 String 객체와 int 기본 자료형을 선언했다면 따로 생성자를 만들지 않아도 된다.
      • ex) Hello hello = new Hello("Hello",1);
  • @Getter,@Setter (Lombok)
    • get,set 메서드를 지원
  • @Id
  • @GeneratedValue(strategy = GenerationType.IDENTITY)
    • 기본 키 생성을 DB에게 맡기는 전략
    • 데이터를 저장할 때 해당 속성에 값을 일일이 입력하지 않아도 자동으로 1씩 증가
  • @ManyToOne, @OneToMany
    • 부모 자식의 관계를 갖는 구조에서 1:N, N:1 관계를 설정하는 어노테이션
  • @PathVariable
    • 경로 변수를 표시하기 위해 메서드에 매개변수로 사용
    • 경로 변수는 {id} 같은 중괄호를 나타낸다.
    • ex) @GetMapping("/exam/{id}")
      ex) @PathVariable Long id;
  • @JpaRepository
    • JpaRepository는 JPA가 제공하는 인터페이스 중 하나로 CRUD 작업을 처리하는 메서드들을 이미 내장하고 있어 데이터 관리 작업을 좀 더 편리하게 처리할 수 있다.
      • CRUD는 Create, Read, Update, Delete의 앞글자만 따 만든 단어로, 데이터 처리의 기본 기능을 의미한다.
  • @Configuration
    • Spring에서 Bean을 수동으로 등록할 때 사용
    • @Bean을 등록할 때 싱글톤이 되도록 보장
      • 스프링 컨테이너에서 Bean을 관리할 수 있게 됨

특정 포트 사용중인 프로세스 킬

  • 특정 포트 사용중인 프로세스 킬
    윈도우(cmd 에서 진행, git bahs 에서는 안됨)
    netstat 종료 : Ctrl + C
  • Window
    • netstat -a -o | findstr 찾을 포트
    • taskkill /f /pid 프로세스번호
  • MAC
    • lsof -i :8080 | grep LISTEN | awk '{print $2}' | xargs kill -9

:: Other

  • 스프링의 의존성 주입(DI, Dependency Injection)이란 스프링이 객체를 대신 생성하여 주입하는 기법을 말한다.
  • 클라이언트 요청 시 새로운 URL로 연결하는 명령어 : redirect
    • ex)
       @GetMapping("/")
        public String root() {
            return "redirect:/question/list";
        }
    • 루트 URL 이동 시 question/list 주소로 연결

0개의 댓글