[Spring] 스프링 부트를 이용한 게시판 프로젝트 - spring boot 세팅하기

전주은·2023년 1월 3일
0
post-thumbnail

😎 스프링 부트 세팅하기

✅ intelliJ IDEA spring initalizr

  • java / Gradle-Groovy / JDK17
  • spring-boot 2.7.7
  • lombok
  • spring data jpa
  • spring web
  • spring boot actuator
  • spring boot devtools
  • MySQL driver

intelliJ community버전도 가능하게 해주는 사이트

✅ application.yaml

debug: false
management.endpoints.web.exposure.include: "*"

logging:
  level:
    com.koreait.projectboard: debug
    org.springframework.web.servlet: debug
    org.hibernate.type.descriptor.sql.BasicBinder: trace

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/❗
    username:password:driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    defer-datasource-initialization: true
    hibernate.ddl-auto: create
    show-sql: true
    properties:
      hibernate.format_sql: true
      hibernate.default_batch_fetch_size: 100
#  h2.console.enabled: true
  sql.init.mode: always
  data.rest:
    base-path: /api
    detection-strategy: annotated #어노테이션을 걸어논 아이만 api에 접근가능 - repo에 어노테이션 추가!
  thymeleaf3.decoupled-logic: true

server.port: 8989

❗ 부분은 컴퓨터마다 다르기때문에 새롭게 설정해 줍니다.

✅ 추가 gradle 설정

plugins {

    id 'java'
    id 'org.springframework.boot' version '2.7.7'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'

}

group = 'com.koreait'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

configurations {

    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    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'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'mysql:mysql-connector-java'
    // 01-02 추가 MockMvc
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.data:spring-data-rest-hal-explorer'

    // query DSL 설정
    implementation "com.querydsl:querydsl-jpa"
    implementation "com.querydsl:querydsl-core"
    implementation "com.querydsl:querydsl-collections"
    annotationProcessor "com.querydsl:querydsl-apt:${dependencyManagement.importedProperties['querydsl.version']}:jpa" // querydsl JPAAnnotationProcessor 사용 지정
    annotationProcessor "jakarta.annotation:jakarta.annotation-api" // java.lang.NoClassDefFoundError (javax.annotation.Generated) 대응 코드
    annotationProcessor "jakarta.persistence:jakarta.persistence-api" // java.lang.NoClassDefFoundError (javax.annotation.Entity) 대응 코드
    
// 타임리프
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

// configuration
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'

// security + thymeleaf 같이 검색했을때 나옴
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
}

tasks.named('test') {
    useJUnitPlatform()

}

// Query DSL 설정 //전역으로 설정할 것
def generated="src/main/generated"

// Query DSL Qclass 파일 생성 위치를 지정
tasks.withType(JavaCompile){
    options.getGeneratedSourceOutputDirectory().set(file(generated))
}

// java source set에 query QClass 위치 추가
sourceSets{
    main.java.srcDirs +=[ generated ]
}

// gradle clean 시에 Qclass 디렉토리를 삭제
clean{
    delete file(generated)

}

✔ MockMvc

웹 어플리케이션을 어플리케이션 서버에 배포하지 않고 테스트용 MVC 환경을 만들어 요청 및 전송,
응답기능을 제공하는 유틸리티 클래스

✔ Query DSL

  • JPA를 좀 더 효율적으로 사용할 수 있는 라이브러리
  • 오픈소스 프로젝트로 JPQL을 Java 코드로 작성할 수 있도록 함
  • 정적 타입을 이용해서 SQL과 같은 쿼리를 생성해줌

Config

java> com.korea.projectboard > config 패키지 생성

  • JpaConfig 클래스 생성
package com.koreait.projectboard.config;


import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.util.Optional;

@EnableJpaAuditing
@Configurable
public class JpaConfig {
    @Bean
    public AuditorAware<String> auditorAware(){//이거 완전 필수!!
        return () -> Optional.of("관리자");
        //스프링 시큐리티로 인증 기능을 붙이게 될 때 수정할거임
    }
}
  • SecurityConfig 클래스 생성
package com.koreait.projectboard.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeRequests(auth -> auth.anyRequest().permitAll())
                .formLogin().and()
                .build();
    }
}
  • ThymeleafConfig 클래스 생성
package com.koreait.projectboard.config;


import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;

@Configuration
public class ThymeleafConfig {
    @Bean
    public SpringResourceTemplateResolver thymeleafTemplateResolver(
            SpringResourceTemplateResolver defaultTemplateResolver,
            Thymeleaf3Properties thymeleaf3Properties
    ) {
        defaultTemplateResolver.setUseDecoupledLogic(thymeleaf3Properties.isDecoupledLogic());
        return defaultTemplateResolver;
    }

    @RequiredArgsConstructor
    @Getter
    @ConstructorBinding
    @ConfigurationProperties("spring.thymeleaf3")
    public static class Thymeleaf3Properties {
        /**
         * Use Thymeleaf 3 Decoupled Logic
         */
        private final boolean decoupledLogic;
    }
}

ProjectBoardAppication

@ConfigurationPropertiesScan을 추가 시켜줍니다!

package com.koreait.projectboard;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@ConfigurationPropertiesScan
@SpringBootApplication
public class ProjectBoardApplication {


    public static void main(String[] args) {
        SpringApplication.run(ProjectBoardApplication.class, args);
    }


}

0개의 댓글