개발 무지렁이

[Spring Boot] 기본세팅 본문

Backend/스프링부트

[Spring Boot] 기본세팅

Gaejirang-e 2022. 11. 26. 12:35

환경설정 ⚙️


[.gitignore]

application-base-addi.yml

[application.properties]

spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.suffix=.html

[application.yml]

spring:
  profiles:
    active: dev, base-addi
  thymeleaf:
    cache: false
    prefix: file:src/main/resources/templates/
  devtools:
    livereload:
      enabled: true
    restart:
      enabled: true
  datasource:
    url: jdbc:mariadb://127.0.0.1:3307/app59?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul
    username: [ username 입력 ]
    password: [ password 입력 ]
    driver-class-name: org.mariadb.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: create
custom:
  genFileDirPath: c:/temp/app59

[application-dev.yml]

server:
    port: 8010

스프링 시큐리티 🔒


[SecurityConfig.java]

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    private final UserSecurityService userSecurityService;
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(
                        csrf -> csrf.disable()
                )
                .authorizeRequests(
                        authorizeRequests -> authorizeRequests
                                .antMatchers("/**")
                                .permitAll()
                )
                .formLogin(
                        formLogin -> formLogin
                                .loginPage("/user/login")
                                .defaultSuccessUrl("/")
                )
                .logout(logout -> logout
                        .logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))
                        .logoutSuccessUrl("/user/login")
                        .invalidateHttpSession(true)
                );
        return http.build();
    }
    // 비밀번호 암호화
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    // 인증
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}

[MemberSecurityService.java]

@Service
@RequiredArgsConstructor
public class MemberSecurityService implements UserDetailsService {
    private final MemberRepository memberRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Member member = memberRepository.findByUsername(username).get();

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("member"));

        return new MemberContext(member, authorities);
    }
}

[dto/MemberContext.java]

@Getter
public class MemberContext extends User {
    private final Long id;
    private final String profileImgUrl;

    public MemberContext(Member member, List<GrantedAuthority> authorities) {
        super(member.getUsername(), member.getPassword(), authorities);
        this.id = member.getId();
        this.profileImgUrl = member.getProfileImgUrl();
    }
}

Query DSL 🌞


[App59Application.java]

@EnableJpaAuditing // **중요
@SpringBootApplication
public class App59Application {
    public static void main(String[] args) {
        SpringApplication.run(App59Application.class, args);
    }

}

[BaseConfig.java]

@Configuration
public class BaseConfig {
    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }
}

생성시각 / 수정시각 🕑


[BaseEntity.java]

@Getter
@SuperBuilder // 상속 받는 자식객체를 만들 때, 부모객체의 필드값도 지정할 수 있게
@MappedSuperclass // 객체 간 공통속성이 존재하여, 이를 부모 클래스에서 선언하여 속성만 상속받아 사용할 수 있게
@NoArgsConstructor(access= PROTECTED)
@EntityListeners(AuditingEntityListener.class) // 해당클래스에서 Auditing 기능을 포함(시간에 대해 자동으로 값을 넣어주는 기능)
@ToString
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @CreatedDate // 엔티티가 생성되어 저장될 때 시간 자동 저장
    private LocalDateTime createDate;

    @LastModifiedDate // 엔티티가 수정될 때 시간 자동 저장
    private LocalDateTime modifyDate;
}

HTML 🎨


<html lang="ko"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      xmlns:th="http://thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      layout:decorate="~{layout/layout.html}"
>
Comments