service/MemberService
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import java.util.List;
import java.util.Optional;
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
/**
* 회원 가입
* @param member
* @return
*/
public Long join(Member member){
//같은 이름이 있는 중복 회원X
long start = System.currentTimeMillis();
try {
validateDuplicateMember(member); //중복 회원 검증
memberRepository.save(member);
return member.getId();
}finally{
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("join ="+timeMs+"ms");
}
}
private void validateDuplicateMember(Member member) {
memberRepository.findByName(member.getName())
.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원입니다.");
});
}
/*
*전체 회원 조회
*/
public List<Member> findMembers(){
long start = System.currentTimeMillis();
try{
return memberRepository.findAll();
}finally{
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("findMembers "+timeMs+"ms");
}
}
public Optional<Member> findOne(Long memberId){
return memberRepository.findById(memberId);
}
}
@Component
@Aspect // 이것을 써야 aop를 쓸 수 있음
public class TimeTraceAop {
@Around("execution(* hello.hellospring..*(..))")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
System.out.println("START: " + joinPoint.toString());
try {
return joinPoint.proceed();
} finally {
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("END: " + joinPoint.toString()+ " " + timeMs + "ms");
}
}
}