
해당 게시글에서는 Spring 프로젝트의 디렉토리 구조와 각 디렉토리가 무엇을 의미하고 어떠한 파일들을 저장하는지에 대해 알아본다.
✍️ 예제 코드 작성
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 생성자, getter, setter 생략
// 비즈니스 로직 예시: 이메일 변경 메서드
public void updateEmail(String newEmail) {
// 검증 로직 등 추가 가능
this.email = newEmail;
}
}
✍️ 예제 코드 작성
public interface UserRepository extends JpaRepository<User, Long> {
// 추가적인 쿼리 메서드 선언 가능
Optional<User> findByEmail(String email);
}
또는 다음과 같이 직접 DAO로 구현 가능.
✍️ 예제 코드 작성
@Repository
public class UserDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findUserById(Long id) {
String sql = "SELECT * FROM users WHERE id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) ->
new User(rs.getLong("id"), rs.getString("name"), rs.getString("email"))
);
}
}
✍️ 예제 코드 작성
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException("사용자를 찾을 수 없습니다"));
}
public User registerUser(User user) {
// 이메일 중복 체크 등 추가 로직 가능
return userRepository.save(user);
}
}
✍️ 예제 코드 작성
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
User user = userService.getUser(id);
// 도메인 객체를 DTO로 변환해서 반환
UserDTO dto = new UserDTO(user.getId(), user.getName(), user.getEmail());
return ResponseEntity.ok(dto);
}
}
✍️ 예제 코드 작성
public class UserDTO {
private Long id;
private String name;
private String email;
public UserDTO(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// getter, setter 생략
}
✍️ 예제 코드 작성
@Configuration
public class AppConfig {
// 예: 빈(bean) 등록
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
✍️ 예제 코드 작성
<!-- resources/templates/user.html (Thymeleaf 예제) -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Info</title>
</head>
<body>
<h1 th:text="${user.name}">User Name</h1>
<p th:text="${user.email}">User Email</p>
</body>
</html>
✍️ 예제 코드 작성
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
// 글로벌 예외 처리 예시
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
✍️ 예제 코드 작성
public class StringUtil {
public static boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
✍️ 예제 코드 작성 (Security)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
✍️ 예제 코드 작성 (Aspect)
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethod(JoinPoint joinPoint) {
System.out.println("메서드 호출: " + joinPoint.getSignature().getName());
}
}
✍️ 예제 코드 작성
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetUser() {
User user = userService.getUser(1L);
assertNotNull(user);
}
}