제어접근자 static, 코드로 알아보자 Part2

서재환·2021년 12월 10일
0

JAVA

목록 보기
5/16

Spring Security 공부하던 도중 알게된 static의 또다른 부분

아래와 같은 코드가 있었다. 코드 내용을 이해 할 필요는 없고 new 연산자나 또는 객체를 사용
하겠다고 클래스 내부에 선언한 부분이 없는데 User.withUsername(customer.getEmail())
라고 사용한 부분이 있다.

User 객체를 클래스 내부에 눈을 씻고 찾아봐도 User class를 사용하겠습니다 하는 부분을 찾
아볼 수 없다. 

User 관련된 code는 import org.springframework.security.core.userdetails.User;
부분이 다이다. 이러한 경우는 어떻게 이해해야 할까?
import com.javadevjournal.jpa.entities.CustomerEntity;
import com.javadevjournal.jpa.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private CustomerRepository customerRepository;

    @Override
    public UserDetails loadUserByUsername(String username) 
    throws UsernameNotFoundException {
        final CustomerEntity customer = customerRepository.findByEmail(username);
        if (customer == null) {
            throw new UsernameNotFoundException(username);
        }
        UserDetails user = User.withUsername(customer.getEmail())
        .password(customer.getPassword())
        .authorities("USER").build();
        return user;
    }
}

정답은 withUsername 함수에 있었다.

intellij 에서 withUsername 이라는 함수 부분을 클릭하면 User class에 선언된 함수라는 것을 알
수 있는데 일부만 발췌해서 가져오면 아래와 같은 형태를 갖고 있다.

자세히 보면 함수 앞에 static 이라는 접근 제어자가 있는데 함수 앞에 static 접근 제어자가 붙을 경우 static
메모리에 해당 함수가 올라가게 돼서 User 모듈을 가져오기만 하면 바로 User.withUsername(String username)
형태로 바로 사용할 수 있는 것이다.

static의 또 하나의 용도를 알게 되었다.

0개의 댓글