Compare commits
22 Commits
spring-sec
...
jackson
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d942818cb7 | ||
|
|
3af79e6619 | ||
|
|
2e63b9b128 | ||
|
|
18aa61f5d5 | ||
|
|
9f9a5644fc | ||
|
|
abcf7da69e | ||
|
|
20ca7b3e17 | ||
|
|
160781432f | ||
|
|
27f91fd501 | ||
|
|
c72d0ff106 | ||
|
|
0d66541289 | ||
|
|
889ff261a8 | ||
|
|
e62b1dd7aa | ||
|
|
5869f3b20a | ||
|
|
1e0696deba | ||
|
|
5ed4f8153a | ||
|
|
5e55eeb462 | ||
|
|
5891775b15 | ||
|
|
a62fbb7f71 | ||
|
|
35a89db2d5 | ||
|
|
3f64ef2977 | ||
|
|
b07abb8703 |
37
놀이터(예제 코드 작성)/jackson/.gitignore
vendored
Normal file
37
놀이터(예제 코드 작성)/jackson/.gitignore
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
44
놀이터(예제 코드 작성)/jackson/build.gradle.kts
Normal file
44
놀이터(예제 코드 작성)/jackson/build.gradle.kts
Normal file
@@ -0,0 +1,44 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
id("org.springframework.boot") version "2.6.1"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
kotlin("jvm") version "1.6.0"
|
||||
kotlin("plugin.spring") version "1.6.0"
|
||||
kotlin("plugin.jpa") version "1.6.0"
|
||||
}
|
||||
|
||||
group = "com.banjjoknim"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
java.sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
|
||||
runtimeOnly("com.h2database:h2")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = listOf("-Xjsr305=strict")
|
||||
jvmTarget = "11"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
BIN
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
놀이터(예제 코드 작성)/jackson/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
놀이터(예제 코드 작성)/jackson/gradlew
vendored
Executable file
234
놀이터(예제 코드 작성)/jackson/gradlew
vendored
Executable file
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
89
놀이터(예제 코드 작성)/jackson/gradlew.bat
vendored
Normal file
89
놀이터(예제 코드 작성)/jackson/gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
놀이터(예제 코드 작성)/jackson/settings.gradle.kts
Normal file
1
놀이터(예제 코드 작성)/jackson/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "jackson"
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class PlaygroundApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<PlaygroundApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
import com.banjjoknim.playground.jackson.jsonserialize.ContextualCarSerializer
|
||||
import com.banjjoknim.playground.jackson.jsonserialize.UsingJsonSerializeAnnotationCarSerializer
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize
|
||||
|
||||
data class Car(
|
||||
val name: String,
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingNoAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingJsonSerializeAnnotationCarSerializer(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = UsingJsonSerializeAnnotationCarSerializer::class)
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingContextualSerializerWithSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = ContextualCarSerializer::class)
|
||||
@field:Secret("hello world!!")
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingContextualSerializerWithNoSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@JsonSerialize(using = ContextualCarSerializer::class)
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
|
||||
data class CarUsingSecretAnnotation(
|
||||
val name: String = "banjjoknim",
|
||||
@field:Secret("****")
|
||||
val secret: String = "secret",
|
||||
val price: Int = 10000000,
|
||||
val owner: Owner = Owner()
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
data class Owner(val name: String = "ban", val age: Int = 30)
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.banjjoknim.playground.jackson.common
|
||||
|
||||
import com.fasterxml.jackson.annotation.JacksonAnnotation
|
||||
|
||||
/**
|
||||
* [jackson-annotations](https://www.baeldung.com/jackson-annotations) 참고.
|
||||
*
|
||||
* @see com.fasterxml.jackson.annotation.JacksonAnnotation
|
||||
* @see com.fasterxml.jackson.annotation.JacksonAnnotationsInside
|
||||
*/
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
@Target(AnnotationTarget.FIELD) // 현재 상황에서는 PROPERTY 로 적용할 경우 제대로 적용되지 않는다. 아마 어노테이션 자체가 자바 기반으로 사용되어 PROPERTY 를 인식하지 못하는 것 같다(자바에서는 PROPERTY 타입을 사용할 수 없음).
|
||||
@JacksonAnnotation // NOTE: important; MUST be considered a 'Jackson' annotation to be seen(or recognized otherwise via AnnotationIntrospect.isHandled())
|
||||
annotation class Secret(
|
||||
val substituteValue: String = ""
|
||||
)
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.banjjoknim.playground.jackson.jsonserialize
|
||||
|
||||
import com.banjjoknim.playground.jackson.common.Car
|
||||
import com.banjjoknim.playground.jackson.common.Secret
|
||||
import com.fasterxml.jackson.core.JsonGenerator
|
||||
import com.fasterxml.jackson.databind.BeanDescription
|
||||
import com.fasterxml.jackson.databind.BeanProperty
|
||||
import com.fasterxml.jackson.databind.JsonSerializer
|
||||
import com.fasterxml.jackson.databind.SerializationConfig
|
||||
import com.fasterxml.jackson.databind.SerializerProvider
|
||||
import com.fasterxml.jackson.databind.introspect.Annotated
|
||||
import com.fasterxml.jackson.databind.introspect.AnnotatedMember
|
||||
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier
|
||||
import com.fasterxml.jackson.databind.ser.ContextualSerializer
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
|
||||
/**
|
||||
* [jackson-object-mapper-tutorial](https://www.baeldung.com/jackson-object-mapper-tutorial) 참고.
|
||||
*
|
||||
* [how-to-(de)serialize-field-from-object-based-on-annotation-using-jackson](https://stackoverflow.com/questions/18659835/how-to-deserialize-field-from-object-based-on-annotation-using-jackson)
|
||||
*
|
||||
* Custom Serializer 를 만들기 위해서는 아래와 같이 StdSerializer<T> 를 상속해야 한다.
|
||||
*
|
||||
* 만약 어노테이션을 이용한 설정 또는 프로퍼티마다 다르게 작동하는 Serializer 를 만들고 싶다면 JsonSerializer 의 add-on interface 인 ContextualSerializer 를 구현하면 된다.
|
||||
*
|
||||
* JsonSerializer<T> 만 확장할 경우엔 애노테이션 정보를 얻을 수 없다. 추가적으로 ContextualSerializer 인터페이스를 구현해주면 createContextual() 메서드를 구현해줘야 하는데 두번째 인자로 넘어오는 BeanProperty 를 이용해 애노테이션 정보를 구할 수 있다.
|
||||
*
|
||||
* ContexutalSerializer 를 사용하는 방법은 [TestContextualSerialization](https://github.com/FasterXML/jackson-databind/blob/master/src/test/java/com/fasterxml/jackson/databind/contextual/TestContextualSerialization.java) 참고하도록 한다.
|
||||
*
|
||||
* Custom Serializer 가 JsonSerializer<T> 와 ContextualSerialier 를 모두 구현할 경우 createContextual() 함수가 먼저 호출된다.
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ser.std.StdSerializer
|
||||
* @see com.fasterxml.jackson.databind.ser.std.StringSerializer
|
||||
* @see com.fasterxml.jackson.databind.ser.ContextualSerializer
|
||||
*/
|
||||
class CarSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeNumberField("price", value.price)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarPriceSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeNumberField("price", value.price)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameOwnerSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeObjectField("owner", value.owner)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class CarNameOwnerNameSerializer : StdSerializer<Car>(Car::class.java) {
|
||||
override fun serialize(value: Car, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeStartObject()
|
||||
gen.writeStringField("name", value.name)
|
||||
gen.writeObjectFieldStart("owner")
|
||||
gen.writeStringField("name", value.owner.name)
|
||||
gen.writeEndObject()
|
||||
}
|
||||
}
|
||||
|
||||
class UsingJsonSerializeAnnotationCarSerializer : StdSerializer<String>(String::class.java) {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString("****")
|
||||
}
|
||||
}
|
||||
|
||||
class ContextualCarSerializer(
|
||||
private val substituteValue: String = "this is default value in ContextualCarSerializer"
|
||||
) : StdSerializer<String>(String::class.java), ContextualSerializer {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString(substituteValue)
|
||||
}
|
||||
|
||||
override fun createContextual(provider: SerializerProvider, property: BeanProperty): JsonSerializer<*> {
|
||||
val annotation = property.getAnnotation(Secret::class.java)
|
||||
if (annotation != null) {
|
||||
return ContextualCarSerializer(annotation.substituteValue)
|
||||
}
|
||||
return ContextualCarSerializer()
|
||||
// JsonMappingException: Can not write a field name, expecting a value (through reference chain: com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithNoSecretAnnotation["secret"])
|
||||
// return provider.findKeySerializer(property.type, property)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AnnotationIntrospector 를 상속한 JacksonAnnotationIntrospector 은 Jackson 라이브러리가 직렬화/역직렬화시 `JacksonAnnotation` 정보를 어떻게 처리할지에 대한 정보가 정의되어 있는 클래스다.
|
||||
*
|
||||
* 따라서 어노테이션별로 어떻게 처리할지 재정의하고 싶다면 이 녀석을 override 해준뒤 ObjectMapper 에 등록해주면 된다.
|
||||
*
|
||||
* 등록할 때는 `ObjectMapper#setAnnotationIntrospector()` 를 사용한다.
|
||||
*
|
||||
* [FasterXML - AnnotationIntrospector](https://github.com/FasterXML/jackson-docs/wiki/AnnotationIntrospector)
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector#
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
*
|
||||
*/
|
||||
class SecretAnnotationIntrospector : JacksonAnnotationIntrospector() {
|
||||
/**
|
||||
*
|
||||
* `@JsonIgnore` 를 적용했을 때 무시할지 여부를 판단하는 함수이다.
|
||||
*
|
||||
* 따라서 직렬화 / 역직렬화시 무시하고 싶은 프로퍼티가 있다면 이 함수를 override 하면 된다.
|
||||
*/
|
||||
override fun hasIgnoreMarker(m: AnnotatedMember): Boolean {
|
||||
return super.hasIgnoreMarker(m)
|
||||
}
|
||||
|
||||
/**
|
||||
* `@JsonSerailize` 가 붙은 어노테이션의 처리를 재정의할 때 override 하는 함수이다.
|
||||
*
|
||||
* 자세한 내용은 JacksonAnnotationIntrospector#findSerializer() 의 구현을 살펴보도록 한다.
|
||||
*
|
||||
* 특정 프로퍼티에 대해 어떤 Serializer 를 사용할 것인지 결정하는 함수이다.
|
||||
*
|
||||
* 따라서 특정 조건에 따라 직렬화 처리에 사용할 Serializer 를 정의하고 싶다면 이 함수를 override 하면 된다.
|
||||
*/
|
||||
override fun findSerializer(a: Annotated): Any? {
|
||||
val annotation = a.getAnnotation(Secret::class.java)
|
||||
if (annotation != null) {
|
||||
return SecretAnnotationSerializer(annotation.substituteValue)
|
||||
}
|
||||
return super.findSerializer(a) // 기존 JacksonAnnotationIntrospector 의 것을 사용한다.
|
||||
}
|
||||
}
|
||||
|
||||
class SecretAnnotationSerializer(private val substituteValue: String) : StdSerializer<String>(String::class.java) {
|
||||
override fun serialize(value: String, gen: JsonGenerator, provider: SerializerProvider) {
|
||||
gen.writeString(substituteValue)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 직렬화될 프로퍼티를 수정하도록 하는 방법이다.
|
||||
*
|
||||
* BeanSerializerModifier#changeProperties() 를 재정의한 뒤,
|
||||
*
|
||||
* SimpleModule 을 이용해서 ObjectMapper 에 등록한다.
|
||||
*
|
||||
* 아래처럼 하면 직렬화 대상에서 완전히 제외된다(`@JsonIgnore`와 동일한 효과).
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanSerializerModifier
|
||||
* @see com.fasterxml.jackson.databind.module.SimpleModule
|
||||
*/
|
||||
class SecretBeanSerializerModifier : BeanSerializerModifier() {
|
||||
override fun changeProperties(
|
||||
config: SerializationConfig,
|
||||
beanDesc: BeanDescription,
|
||||
beanProperties: MutableList<BeanPropertyWriter>
|
||||
): MutableList<BeanPropertyWriter> {
|
||||
SimpleModule()
|
||||
return beanProperties
|
||||
.filter { property -> property.getAnnotation(Secret::class.java) == null }
|
||||
.toMutableList()
|
||||
// return super.changeProperties(config, beanDesc, beanProperties)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.banjjoknim.playground
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class JacksonApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.banjjoknim.playground.jackson.jsonserialize
|
||||
|
||||
import com.banjjoknim.playground.jackson.common.Car
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithNoSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingContextualSerializerWithSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingJsonSerializeAnnotationCarSerializer
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingNoAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.CarUsingSecretAnnotation
|
||||
import com.banjjoknim.playground.jackson.common.Owner
|
||||
import com.fasterxml.jackson.databind.AnnotationIntrospector
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule
|
||||
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Nested
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/**
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
* @see com.fasterxml.jackson.databind.module.SimpleModule
|
||||
* @see com.fasterxml.jackson.databind.ser.DefaultSerializerProvider
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanSerializer -> 객체를 직렬화할때 사용되는 Serializer
|
||||
* @see com.fasterxml.jackson.core.json.WriterBasedJsonGenerator
|
||||
* @see com.fasterxml.jackson.databind.ser.std.BeanSerializerBase
|
||||
* @see com.fasterxml.jackson.databind.ser.BeanPropertyWriter
|
||||
*/
|
||||
class CarSerializersTest {
|
||||
|
||||
private lateinit var mapper: ObjectMapper
|
||||
|
||||
companion object {
|
||||
private val owner = Owner("ban", 30)
|
||||
private val car = Car("banjjoknim", 10_000_000, owner)
|
||||
private val carUsingNoAnnotation = CarUsingNoAnnotation()
|
||||
private val carUsingJsonSerializeAnnotationCarSerializer = CarUsingJsonSerializeAnnotationCarSerializer()
|
||||
private val carUsingContextualSerializerWithSecretAnnotation =
|
||||
CarUsingContextualSerializerWithSecretAnnotation()
|
||||
private val carUsingContextualSerializerWithNoSecretAnnotation =
|
||||
CarUsingContextualSerializerWithNoSecretAnnotation()
|
||||
private val carUsingSecretAnnotation = CarUsingSecretAnnotation()
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
mapper = ObjectMapper().registerKotlinModule()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `기본 ObjectMapper의 동작을 테스트한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@DisplayName("등록된 커스텀 직렬화기의 동작을 테스트한다")
|
||||
@Nested
|
||||
inner class CarSerializerTestCases {
|
||||
@Test
|
||||
fun `자동차의 모든 필드만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","price":10000000}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim"}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 가격만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarPriceSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"price":10000000}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름과 오너의 모든 필드를 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameOwnerSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `자동차의 이름과 오너의 이름만 직렬화한다`() {
|
||||
// given
|
||||
val module = SimpleModule()
|
||||
module.addSerializer(Car::class.java, CarNameOwnerNameSerializer())
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val result = mapper.writeValueAsString(car)
|
||||
|
||||
// then
|
||||
assertThat(result).isEqualTo("""{"name":"banjjoknim","owner":{"name":"ban"}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `아무 어노테이션도 적용하지 않고 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingNoAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"secret","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@JsonSerialize 어노테이션을 적용하여 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingJsonSerializeAnnotationCarSerializer)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"****","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ContextualSerializer 를 상속 받은 구현체를 이용해서 직렬화한다`() {
|
||||
// given
|
||||
|
||||
// when
|
||||
val actualWithSecretAnnotation = mapper.writeValueAsString(carUsingContextualSerializerWithSecretAnnotation)
|
||||
val actualWithNoSecretAnnotation =
|
||||
mapper.writeValueAsString(carUsingContextualSerializerWithNoSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actualWithSecretAnnotation).isEqualTo("""{"name":"banjjoknim","secret":"hello world!!","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
assertThat(actualWithNoSecretAnnotation).isEqualTo("""{"name":"banjjoknim","secret":"this is default value in ContextualCarSerializer","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@Secret 어노테이션, AnnotationIntrospector 을 적용하여 직렬화한다`() {
|
||||
// given
|
||||
mapper.setAnnotationIntrospector(SecretAnnotationIntrospector())
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","secret":"****","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `@Secret 어노테이션, BeanSerializerModifier 를 적용하여 직렬화한다`() {
|
||||
// given
|
||||
val module = object : SimpleModule() {
|
||||
override fun setupModule(context: SetupContext) {
|
||||
super.setupModule(context)
|
||||
context.addBeanSerializerModifier(SecretBeanSerializerModifier())
|
||||
}
|
||||
}
|
||||
mapper.registerModule(module)
|
||||
|
||||
// when
|
||||
val actual = mapper.writeValueAsString(carUsingSecretAnnotation)
|
||||
|
||||
// then
|
||||
assertThat(actual).isEqualTo("""{"name":"banjjoknim","price":10000000,"owner":{"name":"ban","age":30}}""")
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Kotlin + Spring Boot 를 사용한다면 `com.fasterxml.jackson.module:jackson-module-kotlin` 의존성을 사용할 것이다.
|
||||
*
|
||||
* 이를 사용하면 기본 생성자 없이도 `@RequestBody` 에서 json 을 객체로 역직렬화 할 수 있다.
|
||||
*
|
||||
* `com.fasterxml.jackson.module:jackson-module-kotlin` 에서 이러한 역할을 해주는 것이 KotlinAnnotationIntrospector 이다.
|
||||
*
|
||||
* 하지만 새로운 AnnotationIntrospector 를 등록하면 KotlinAnnotationIntrospector 가 무시되어 기본생성자 없이는 `@RequestBody` 객체를 만들지 못하게 된다.
|
||||
*
|
||||
* 따라서 아래와 같이 기존의 AnnotationIntrospector 도 등록해주어야 한다.
|
||||
*
|
||||
* 이는 AnnotationIntrospector.Pair 도우미 클래스를 사용해서 할 수 있다.
|
||||
*
|
||||
* 이때, 순서대로 기본 Introspector, 보조 Introspector 로 등록된다.
|
||||
*
|
||||
* [AnnotationIntrospector](https://github.com/FasterXML/jackson-docs/wiki/AnnotationIntrospector)
|
||||
*
|
||||
* @see com.fasterxml.jackson.databind.ObjectMapper
|
||||
* @see com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair
|
||||
* @see com.fasterxml.jackson.databind.AnnotationIntrospector
|
||||
* @see com.fasterxml.jackson.module.kotlin.KotlinAnnotationIntrospector
|
||||
*/
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot를 사용하면 기본적으로 3가지의 AnnotationIntrospector 가 ObjectMapper 에 존재한다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(originalAnnotationIntrospector.allIntrospectors()).hasSize(3)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("KotlinAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[1]).isEqualTo("JacksonAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[2]).isEqualTo("KotlinNamesAnnotationIntrospector")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot 를 사용할 시 ObjectMapper 에 새로운 AnnotationIntrospector 를 추가하면 KotlinAnnotationIntrospector 가 무시된다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
mapper.setAnnotationIntrospector(SecretAnnotationIntrospector())
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(originalAnnotationIntrospector.allIntrospectors()).hasSize(3)
|
||||
assertThat(allIntrospectorNames).hasSize(1)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("SecretAnnotationIntrospector")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Kotlin + Spring Boot 를 사용할 시 ObjectMapper 에 새로운 AnnotationIntrospector 를 추가할 때 Pair 로 추가하면 KotlinAnnotationIntrospector 가 무시되지 않는다`() {
|
||||
// given
|
||||
val originalAnnotationIntrospector = mapper.serializationConfig.annotationIntrospector
|
||||
|
||||
// when
|
||||
mapper.setAnnotationIntrospector(
|
||||
AnnotationIntrospector.pair(
|
||||
SecretAnnotationIntrospector(),
|
||||
originalAnnotationIntrospector
|
||||
) // 내부 구현은 아래와 같다.
|
||||
// AnnotationIntrospectorPair(SecretAnnotationIntrospector(), originalAnnotationIntrospector)
|
||||
)
|
||||
val allIntrospectorNames = mapper.serializationConfig.annotationIntrospector.allIntrospectors()
|
||||
.map { annotationIntrospector -> annotationIntrospector::class.simpleName }
|
||||
|
||||
// then
|
||||
assertThat(allIntrospectorNames).hasSize(4)
|
||||
assertThat(allIntrospectorNames[0]).isEqualTo("SecretAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[1]).isEqualTo("KotlinAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[2]).isEqualTo("JacksonAnnotationIntrospector")
|
||||
assertThat(allIntrospectorNames[3]).isEqualTo("KotlinNamesAnnotationIntrospector")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,20 @@ import org.springframework.stereotype.Service
|
||||
* 구글과 페이스북 측에서 우리에게 보내는 Request에 액세스 토큰과 사용자 정보등의 OAUth2 정보가 모두 포함되어 있다.
|
||||
*
|
||||
* 하지만 네이버, 카카오는 스프링 부트에서 기본적인 정보를 제공하지 않기 때문에 따로 해당 정보를 제공하는 클래스를 작성해야 한다.
|
||||
*
|
||||
* 우리는 OAuth2-Client 라는 라이브러리를 사용하고 있다.
|
||||
*
|
||||
* OAuth2-Client 라이브러리는 구글, 페이스북, 깃허브 등의 Provider를 기본적으로 제공해주지만, 네이버 카카오는 제공해주지 않는다.
|
||||
*
|
||||
* 이는 각 나라별로 OAuth2 를 지원해주는 서드 파티가 제공하는 attribute 가 모두 다르기 때문이다. 그래서 현실적으로 모든 곳을 지원해줄 수가 없다.
|
||||
*
|
||||
* OAuth2-Client 는 OAuth2ClientProperties 라는 클래스를 통한 자동 설정을 지원해주고 있다.
|
||||
*
|
||||
* OAuth2는 여러가지 방식이 있다. Authorization Code Grant Type 방식 등등..
|
||||
*
|
||||
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties
|
||||
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter
|
||||
* @see org.springframework.security.config.oauth2.client.CommonOAuth2Provider
|
||||
*/
|
||||
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록되도록 해준다.
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) // 스프링 시큐리티 관련 특정 어노테이션에 대한 활성화 설정을 할 수 있다.
|
||||
@@ -172,8 +186,8 @@ class PrincipalDetails(
|
||||
* 이때 UserDetailsService 타입으로 등록되어 있는 빈을 찾아서 해당 빈에 정의된 loadUserByUsername() 을 실행한다.
|
||||
* ```
|
||||
*
|
||||
* @see DaoAuthenticationProvider
|
||||
* @see AbstractUserDetailsAuthenticationProvider
|
||||
* @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
|
||||
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
|
||||
*/
|
||||
@Service
|
||||
class PrincipalDetailService(private val userRepository: UserRepository) : UserDetailsService {
|
||||
@@ -200,9 +214,9 @@ class PrincipalDetailService(private val userRepository: UserRepository) : UserD
|
||||
* OAuth2UserRequest 정보를 이용해서 loadUser 함수 호출 -> 구글로부터 회원프로필을 받아준다.
|
||||
* ```
|
||||
*
|
||||
* @see OAuth2UserService
|
||||
* @see DefaultOAuth2UserService
|
||||
* @see OAuth2UserRequest
|
||||
* @see org.springframework.security.oauth2.client.userinfo.OAuth2UserService
|
||||
* @see org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService
|
||||
* @see org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest
|
||||
*/
|
||||
@Service
|
||||
class PrincipalOAuth2UserService(
|
||||
|
||||
@@ -5,7 +5,8 @@ enum class OAuth2Type(
|
||||
private val createUserInfo: (attributes: Map<String, Any?>) -> OAuth2UserInfo
|
||||
) {
|
||||
GOOGLE("google", { attributes -> GoogleUserInfo(attributes) }),
|
||||
FACEBOOK("facebook", { attributes -> FacebookUserInfo(attributes) });
|
||||
FACEBOOK("facebook", { attributes -> FacebookUserInfo(attributes) }),
|
||||
NAVER("naver", { attributes -> NaverUserInfo(attributes) });
|
||||
|
||||
fun createOAuth2UserInfo(attributes: Map<String, Any?>): OAuth2UserInfo {
|
||||
return createUserInfo(attributes)
|
||||
|
||||
@@ -53,5 +53,33 @@ class FacebookUserInfo(
|
||||
override fun getName(): String {
|
||||
return attributes["name"] as String
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class NaverUserInfo(
|
||||
/**
|
||||
* DefaultOAuth2Service#loadUser(OAuth2UserRequest)
|
||||
* ```kotlin
|
||||
* val oAuth2User = super.loadUser(userRequest)
|
||||
* val attributes = oAuth2User.attributes
|
||||
* ```
|
||||
*/
|
||||
private val attributes: Map<String, Any?>
|
||||
): OAuth2UserInfo {
|
||||
private val response = attributes["response"] as Map<*, *>
|
||||
|
||||
override fun getProviderId(): String {
|
||||
return response["id"] as String
|
||||
}
|
||||
|
||||
override fun getProvider(): String {
|
||||
return "naver"
|
||||
}
|
||||
|
||||
override fun getEmail(): String {
|
||||
return response["email"] as String
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return response["name"] as String
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,16 +64,13 @@ class UserController {
|
||||
* @see PrincipalDetailsService
|
||||
*
|
||||
*/
|
||||
@GetMapping("/login") // OAuth2 로그인 및 일반 로그인 모두 principalDetails 로 세션 정보를 얻어올 수 있다.
|
||||
@GetMapping("/login") // OAuth2 로그인 및 일반 로그인 모두 principalDetails 로 세션 정보를 얻어올 수 있다(다운 캐스팅을 하지 않아도 된다!).
|
||||
fun login(@AuthenticationPrincipal principalDetails: PrincipalDetails) { // DI(의존성 주입)
|
||||
println("principalDetailsUser : ${principalDetails.user}")
|
||||
}
|
||||
|
||||
@GetMapping("/test/login")
|
||||
fun testLogin(
|
||||
authentication: Authentication,
|
||||
@AuthenticationPrincipal userDetails: UserDetails
|
||||
) { // DI(의존성 주입)
|
||||
fun testLogin(authentication: Authentication, @AuthenticationPrincipal userDetails: UserDetails) { // DI(의존성 주입)
|
||||
val principalDetailsFromAuthentication = authentication.principal as PrincipalDetails // 다운 캐스팅
|
||||
println("principalDetailsFromAuthentication : ${principalDetailsFromAuthentication.user}")
|
||||
println("principalDetailsFromAuthentication : ${principalDetailsFromAuthentication.username}")
|
||||
@@ -83,10 +80,7 @@ class UserController {
|
||||
}
|
||||
|
||||
@GetMapping("/test/oauth2/login")
|
||||
fun testOAuth2Login(
|
||||
authentication: Authentication,
|
||||
@AuthenticationPrincipal oauth: OAuth2User
|
||||
) { // DI(의존성 주입)
|
||||
fun testOAuth2Login(authentication: Authentication, @AuthenticationPrincipal oauth: OAuth2User) { // DI(의존성 주입)
|
||||
val oAuth2User = authentication.principal as OAuth2User // 다운 캐스팅
|
||||
println("authentication : ${oAuth2User.attributes}") // OAuth2Service 의 super.loadUser(userRequest).attributes 와 같다.
|
||||
println("oAuth2User : ${oauth.attributes}")
|
||||
|
||||
@@ -16,3 +16,20 @@ spring:
|
||||
scope:
|
||||
- email
|
||||
- public_profile
|
||||
|
||||
naver:
|
||||
client-id: my-naver-client-id
|
||||
client-secret: my-naver-client-secret
|
||||
scope:
|
||||
- name
|
||||
- email
|
||||
client-name: Naver
|
||||
authorization-grant-type: authorization_code
|
||||
redirect-uri: http://localhost:8080/login/oauth2/code # 구글이나 페이스북은 기본적으로 설정되어 있기 때문에 작성하지 않아도 된다. 반면, 구글이나 페이스북은 주소가 고정되어 있으니 함부로 변경하면 안된다.
|
||||
|
||||
provider: # provider를 직접 등록해준다.
|
||||
naver: # /oauth2/authorization/naver 라는 uri를 타고 이동하면 아래의 authorization-uri 로 이동된다.
|
||||
authorization-uri: https://nid.naver.com/oauth2.0/authorize
|
||||
token-uri: https://nid.naver.com/oauth2.0/token
|
||||
user-info-uri: https://openapi.naver.com/v1/nid/me
|
||||
user-name-attribute: response # 회원정보를 json으로 받는데 response라는 키값으로 네이버가 리턴해준다.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<head lang="ko">
|
||||
<meta charset="utf-8">
|
||||
<title>로그인 페이지</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>로그인 페이지</h1>
|
||||
<hr/>
|
||||
<form action="/login" method="post">
|
||||
<input type="text" name="username" placeholder="Username"/><br/>
|
||||
<input type="password" name="password" placeholder="Password"/><br/>
|
||||
<button>로그인</button>
|
||||
</form>
|
||||
<a href="/oauth2/authorization/google">구글 로그인</a>
|
||||
<a href="/oauth2/authorization/facebook">페이스북 로그인</a>
|
||||
<a href="/oauth2/authorization/naver">네이버 로그인</a>
|
||||
<a href="/joinForm">회원가입을 아직 하지 않으셨나요?</a>
|
||||
</body>
|
||||
Reference in New Issue
Block a user