이제 DB를 이용해서 유저를 관리해 보자.

의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

엔티티 생성

@Entity
public class Account {

	@Id @GeneratedValue
	private Integer id;

	@Column(unique = true)
	private String username;

	private String password;

	private String role;

	// ... getter, setter
}

레포지토리 생성

public interface AccountRepository extends JpaRepository<Account, Integer> {
}

중요한 서비스 생성

@Service
public class AccountService implements UserDetailsService {

	private final AccountRepository accountRepository;

	public AccountService(AccountRepository accountRepository) {
		this.accountRepository = accountRepository;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Account account = accountRepository.findByUsername(username);
		if (account == null) {
			throw new UsernameNotFoundException(username);
		}

		return User.builder()
				.username(account.getUsername())
				.password(account.getPassword())
				.roles(account.getRole())
				.build();
	}
}

유저 정보 추가