본문 바로가기

Programming/Spring Boot

[Spring Boot] Spring Boot의 구조와 역할

 

 

 

Controller

 

@RestController
public class TestController {
    @Autowired
    PersonService personService;

    @GetMapping("/test1")
    public String test1(){
        String result = "";

        List<PersonEntity> people = personService.findAll();

        for(PersonEntity item: people){
            result += item.getId()+" "+item.getName()+" "
            	+item.getAge()+" "+item.getAddress() +" / ";
        }

        return result;
    }

    @GetMapping("/test2")
    public String test2(){
        String result = "";

        List<PersonEntity> people = personService.findByName("지현");

        result += people.get(0).getId()+" "+people.get(0).getName()+" "
        	+people.get(0).getAge()+" "+people.get(0).getAddress();

        return result;
    }
}

 

     - 웹 계층

     - HTTP 요청과 응답

 

 

 

 

 

Service

 

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;

    public List<PersonEntity> findAll() {
        List<PersonEntity> people = personRepository.findAll();
        return people;
    }

    public List<PersonEntity> findByName(String name) {
        List<PersonEntity> people = personRepository.findByName(name);
        return people;
    }

    public List<PersonEntity> findByNameLike(String name) {
        List<PersonEntity> people = personRepository.findByNameLike(name);
        return people;
    }

    public PersonEntity save(PersonEntity person) {
        return personRepository.save(person);
    }

    public void deleteById(Long id) {
        personRepository.deleteById(id);
    }
}

 

     - Repository와 Dto를 통해 DB에 접근하여 프로세스를 처리함

     - 비지니스 로직

     - 트랜잭션 처리

 

 

 

 

 

DTO(VO)

 

public class PersonDto {
    private Long id;
    private String name;
    private int age;
    private String address;
}

 

     - 데이터 전송 객체로 Service나 Controller에서 DB에 접근할 때 사용하는 클래스

     - 생략하는 경우도 있음

     - DTO와 Domain을 구분하는 이유는 코드 수정이 발생할 경우 Domain을 수정하게 되면 너무 많은 것에 영향이 가기 때문에 DTO를 사용하여 수정이 필요한 제한적인 부분만 수정하고, 그 부분에 대해서만 영향이 가게 됨 

     - VO는 read only의 속성을 가짐

 

 

 

 

 

Repository(DAO)

 

@Repository
public interface PersonRepository extends JpaRepository<PersonEntity, Long> {
    public List<PersonEntity> findByName(String name);
    public List<PersonEntity> findByNameLike(String name);
}

 

     - JPA를 통해 DB에 직접 접근

     - Interface의 모음

 

 

 

 

 

Domain(Entity)

 

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity(name="person")
public class PersonEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private int age;
    private String address;
}

 

     - DB 테이블과 맵핑되는 엔티티의 모음

 

 

 

 

 

reference

     - Spring Boot 구조 정리

        https://blog.kyojs.com/spring&spring%20boot/2021/07/09/spring_boot1/