Comments (2)
setter 없이도 @requestbody나 @responsebody(@RestController)를 통해 'JSON <-> 객체' 바인딩이 가능한지 궁금해서 찾아보니
@requestbody로 JSON 형식 메시지를 객체(DTO)로 받아올 때 Jackson 라이브러리의 컨버터가 동작하는데
- Jackson의 ObjectMapper가 기본 생성자를 사용하여 객체를 만들고,
- 값을 넣어줄 때는 JSON 필드의 이름을 객체의 getter 혹은 setter 메소드의 이름과 대조해서 넣어준다하네.
- 여기서 객체를 만들거나 값을 넣어주는데 reflection을 사용한다 하는데 이 부분은 모르겠네.
따라서 requestDto에는 기본 생성자와 getter 혹은 setter는 필수로 넣어줘야 하나봐.
- 근데 또 기본 생성자나 getter, setter가 없어도 생성자가 1개만 있으면 자동으로 @JsonCreator를 생성자에 붙여줘서 객체로 받을 수 있게 해준다고 하네...
결론적으로 우리는 다 getter가 붙어있어서 setter를 제거해도 'JSON -> 객체' 바인딩이 가능해.
객체 -> JSON 바인딩 때도 Jackson이 쓰이니까 같은 원리로 동작한다고 생각해.
이때는 어차피 우리가 객체를 생성해서 넘기는 거니까 responseDto에 기본 생성자는 없어도 될테고, getter는 다 있으니까 setter를 제거해도 될 거 같아.
from boardproject.
Reflection API는 쉽게 말하자면,
런타임시에 해당 클래스나 객체의 정보를 읽어내서 값을 수정할 수 있는 기술인거 같아.
특히, Proxy Pattern이나 스프링의 AOP를 구현할때도 내부적으로 쓰이는 기술 중 하나로 알고있어.
신기하게도, getter나 setter 없이도 가능하고 심지어 private 접근 지정자인 필드에 접근해서 값을 넣어줄 수 있어.
(이건 내가 한창 Reflection API에 관심있어서 찾아본 영상 중 하나인데, 나름 신기했음
스프링의 @Autowired 기능을 Reflection API로 구현한 영상 - https://youtu.be/67YdHbPZJn4?t=722)
결론은 DTO에 기본 생성자와 getter만 넣어두면 된다는 말인거 같은데,
나도 잠깐 조사해보니 위에서 말한 1, 2번 말이 그대로 나오는거 같네.
(조사 링크)
setter를 붙이는 것보단 getter를 사용함으로써 값의 변경 위험도를 줄일 수 있어서 getter를 사용하는게 나아보이고,
기본 생성자는 필수이므로 @NoArgsConstructor를 붙여줘야 하나보네.
아주 유익한 정보였다!
from boardproject.
Related Issues (6)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from boardproject.