Notice
Recent Posts
Recent Comments
Link
개발 무지렁이
[Spring Boot] 기본세팅 본문
환경설정 ⚙️
[.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}"
>
'Backend > 스프링부트' 카테고리의 다른 글
[Spring Boot] 서비스(Service)와 에러처리 (0) | 2022.11.27 |
---|---|
[Spring Boot] File 객체와 MultipartFile 인터페이스 (0) | 2022.11.26 |
[Spring Boot] 쿠키(Cookie)와 세션(Session), CSRF (0) | 2022.11.26 |
[Spring Boot] 리포지터리 CRUD 메서드 테스트 (0) | 2022.11.25 |
[Spring Boot] ORM의 표준스펙 JPA 및 엔티티(Entity) (0) | 2022.11.25 |
Comments