[TIL] 25.02.09 SUN - 25.02.10 MON

GDORI·2025년 2월 10일
0

TIL

목록 보기
183/184
post-thumbnail

간단한 스프링부트 서버

일요일에 간단하게 강의 듣고 문제 저장 조회만 구현했다. 데이터 저장은 JPA 스프링데이터를 이용했다.
스프링부트를 체험느낌으로 해봤는데, 배워야 할 내용이 광범위해서 짧은 시간내에 마스터하기는 쉽지 않을 것 같으나 배워두면 좋을 것 같긴 하다. 자동 설정 기능을 제공해서 비즈니스 로직 구현에 집중할 수 있고 지원하는 프레임워크가 많으며 활발한 커뮤니티로 문제 해결이나 새로운 기능 학습에 많은 도움을 받을 수 있을 것 같다.

잘못된 방식일 수 있으니 코드 일부만 올린다..

config

스프링 컨테이너 안 빈으로 등록하여 싱글톤으로 가져다쓸 수 있게 스프링부트 설정을 할 수 있다.

@Configuration
public class SpringConfig {
    private final QuestionRepository questionRepository;
    private final KeywordRepository keywordRepository;

    @Autowired
    public SpringConfig(QuestionRepository questionRepository, KeywordRepository keywordRepository) {
        this.questionRepository = questionRepository;
        this.keywordRepository = keywordRepository;
    }

    @Bean
    public KeywordService keywordService() {
        return new KeywordService(this.questionRepository, this.keywordRepository);
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        return objectMapper;
    }
}

controller

@RestController
public class KeywordController {
    private final KeywordService keywordService;

    @Autowired
    public KeywordController(KeywordService keywordService) {
        this.keywordService = keywordService;
    }

    @GetMapping("/keyword")
    public ResponseEntity<Message> loadKeyword(){

        List<QuestionDto> result = keywordService.getAllQuestions();

        
        // 헤더 생성 및 설정
        HttpHeaders headers= new HttpHeaders();
        headers.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));

        // 반환 메세지 인스턴스 생성
        Message message = new Message(StatusEnum.OK,"성공",result);
        
        return new ResponseEntity<Message>(message,headers, HttpStatus.OK);
    }


    @PostMapping("/keyword")
    public ResponseEntity<Message> addKeyword(@RequestBody Question question){

        // 키워드 등록
        QuestionEntity result = keywordService.saveQuestion(question);

        // 헤더 생성 및 설정
        HttpHeaders headers= new HttpHeaders();
        headers.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));

        // 반환 메세지 인스턴스 생성
        Message message = new Message(StatusEnum.OK,"성공",result);


        return new ResponseEntity<Message>(message,headers, HttpStatus.OK);
    }
}

service

public class KeywordService {


    private final QuestionRepository questionRepository;
    private final KeywordRepository keywordRepository;

    public KeywordService(QuestionRepository questionRepository, KeywordRepository keywordRepository) {
        this.questionRepository = questionRepository;
        this.keywordRepository = keywordRepository;
    }

    public List<QuestionDto> getAllQuestions() {
        return questionRepository.findAll().stream().map(question -> {
            QuestionDto dto = new QuestionDto();
            dto.setQuestionId(question.getQuestion_id());
            dto.setTitle(question.getTitle());
            dto.setDescription(question.getDescription());
            dto.setKeywords(question.getKeywords().stream().map(KeywordEntity::getTag).collect(Collectors.toList()));
            return dto;
        }).collect(Collectors.toList());
    }

    public QuestionEntity saveQuestion(Question keyword) {

        // question 엔터티 생성
        QuestionEntity question = new QuestionEntity();
        question.setTitle(keyword.getTitle());
        question.setDescription(keyword.getDescription());

        // question 저장
        QuestionEntity savedQuestion = questionRepository.save(question);

        String[] keywords = keyword.getKeywords();

        // keyword 저장
        Arrays.stream(keywords).forEach(tag -> {
            KeywordEntity k = new KeywordEntity();
            k.setTag(tag);
            k.setQuestion(savedQuestion);
            keywordRepository.save(k);
        });

        return savedQuestion;
    }
}
profile
하루 최소 1시간이라도 공부하자..

0개의 댓글

관련 채용 정보