├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── CleanArchitectureDemoApplication.java │ │ │ ├── domain │ │ │ ├── Dummy.java │ │ │ ├── DummyRepository.java │ │ │ └── InvalidDummmyException.java │ │ │ ├── infrastructure │ │ │ ├── controllers │ │ │ │ ├── DummyController.java │ │ │ │ ├── SharedExceptionHandler.java │ │ │ │ └── forms │ │ │ │ │ └── CreateDummyDataForm.java │ │ │ └── database │ │ │ │ └── repositories │ │ │ │ └── DummyJpaRepository.java │ │ │ └── use_cases │ │ │ ├── CreateDummyData.java │ │ │ └── GetAllDummyData.java │ └── resources │ │ ├── application.yml │ │ └── db │ │ ├── changelog │ │ └── db.changelog-master.xml │ │ └── mappings │ │ └── dummy.xml └── test │ └── java │ └── com │ └── example │ └── demo │ ├── domain │ └── DummyUTest.java │ ├── infrastructure │ ├── controllers │ │ ├── DummyControllerITest.java │ │ ├── DummyControllerUTest.java │ │ └── forms │ │ │ └── CreateDummyDataFormUTest.java │ └── database │ │ └── repositories │ │ └── DummyJpaRepositoryITest.java │ └── use_cases │ ├── CreateDummyDataUTest.java │ └── GetAllDummyDataUTest.java └── tools └── check-clean-architecture.sh /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | /out/ 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - openjdk11 5 | 6 | jobs: 7 | include: 8 | - stage: build 9 | script: ./gradlew clean assemble 10 | - stage: test 11 | script: ./gradlew clean check 12 | - stage: mutation 13 | script: ./gradlew clean pitest 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-clean-architecture-demo 2 | 3 | [![Build Status](https://travis-ci.org/damienbeaufils/spring-boot-clean-architecture-demo.svg?branch=master)](https://travis-ci.org/damienbeaufils/spring-boot-clean-architecture-demo) 4 | 5 | An example of clean architecture with Spring Boot 6 | 7 | ## Foreword 8 | 9 | This application is designed using a [Clean Architecture pattern](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) (also known as [Hexagonal Architecture](http://www.maximecolin.fr/uploads/2015/11/56570243d02c0_hexagonal-architecture.png)). 10 | Therefore [SOLID principles](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) are used in code, especially the [Dependency Inversion Principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle) (do not mix up with the classic dependency injection in Spring for example). 11 | 12 | Concretely, there are 3 main packages: `domain`, `use_cases` and `infrastructure`. These packages have to respect these rules: 13 | - `domain` contains the business code and its logic, and has no outward dependency: nor on frameworks (Hibernate for example), nor on `use_cases` or `infrastructure` packages. 14 | - `use_cases` is like a conductor. It will depend only on `domain` package to execute business logic. `use_cases` should not have any dependencies on `infrastructure`. 15 | - `infrastructure` contains all the technical details, configuration, implementations (database, web services, etc.), and must not contain any business logic. `infrastructure` has dependencies on `domain`, `use_cases` and frameworks. 16 | 17 | ## Install 18 | 19 | ``` 20 | ./gradlew assemble 21 | ``` 22 | 23 | ## Test 24 | 25 | ``` 26 | ./gradlew check 27 | ``` 28 | 29 | ## Mutation testing 30 | 31 | ``` 32 | ./gradlew pitest 33 | ``` 34 | 35 | ## Run 36 | 37 | ``` 38 | ./gradlew bootRun 39 | ``` 40 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.1.0.RELEASE' 4 | pitestGradlePluginVersion = '1.3.0' 5 | pitestJunit5PluginVersion = '0.8' 6 | } 7 | repositories { 8 | mavenCentral() 9 | } 10 | configurations.maybeCreate('pitest') 11 | dependencies { 12 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 13 | classpath("info.solidsoft.gradle.pitest:gradle-pitest-plugin:${pitestGradlePluginVersion}") 14 | pitest("org.pitest:pitest-junit5-plugin:${pitestJunit5PluginVersion}") 15 | } 16 | } 17 | 18 | apply plugin: 'java' 19 | apply plugin: 'eclipse' 20 | apply plugin: 'org.springframework.boot' 21 | apply plugin: 'io.spring.dependency-management' 22 | apply plugin: 'info.solidsoft.pitest' 23 | 24 | pitest { 25 | pitestVersion = '1.4.3' 26 | testPlugin = 'junit5' 27 | targetClasses = ['com.example.demo.*'] 28 | outputFormats = ['XML', 'HTML'] 29 | } 30 | 31 | version = '1.0.0-SNAPSHOT' 32 | sourceCompatibility = 11 33 | targetCompatibility = 11 34 | 35 | repositories { 36 | mavenCentral() 37 | } 38 | 39 | dependencies { 40 | implementation("org.apache.commons:commons-lang3") 41 | implementation('org.liquibase:liquibase-core') 42 | implementation('org.springframework.boot:spring-boot-starter-data-jpa') 43 | implementation('org.springframework.boot:spring-boot-starter-web') 44 | 45 | runtimeOnly('com.h2database:h2') 46 | runtimeOnly('org.postgresql:postgresql') 47 | runtimeOnly('org.springframework.boot:spring-boot-devtools') 48 | 49 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 50 | // Exclude JUnit 4 51 | exclude group: 'junit' 52 | } 53 | testImplementation("org.junit.jupiter:junit-jupiter-api") 54 | testImplementation("org.junit.platform:junit-platform-runner") 55 | testImplementation("org.mockito:mockito-junit-jupiter") 56 | 57 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") 58 | } 59 | 60 | test { 61 | useJUnitPlatform() 62 | testLogging { 63 | events "passed", "skipped", "failed" 64 | } 65 | } 66 | 67 | task checkCleanArchitecture(type: Exec) { 68 | commandLine 'tools/check-clean-architecture.sh' 69 | } 70 | check.dependsOn checkCleanArchitecture 71 | 72 | wrapper { 73 | gradleVersion = '4.10.2' 74 | } 75 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/damienbeaufils/spring-boot-clean-architecture-demo/3222a57b407e23557fe6779ead5edca3d0cae870/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/CleanArchitectureDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CleanArchitectureDemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(CleanArchitectureDemoApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/domain/Dummy.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | 5 | public class Dummy { 6 | 7 | private Long id; 8 | 9 | private String value; 10 | 11 | public Dummy() { 12 | // Default constructor is required for JPA 13 | } 14 | 15 | public Dummy(String value) { 16 | if (StringUtils.isEmpty(value)) { 17 | throw new InvalidDummmyException("value cannot be null or empty"); 18 | } 19 | this.value = value; 20 | } 21 | 22 | public Long getId() { 23 | return id; 24 | } 25 | 26 | public void setId(Long id) { 27 | this.id = id; 28 | } 29 | 30 | public String getValue() { 31 | return value; 32 | } 33 | 34 | public void setValue(String value) { 35 | this.value = value; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/domain/DummyRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | import java.util.List; 4 | 5 | public interface DummyRepository { 6 | 7 | Dummy save(Dummy dummy); 8 | 9 | List findAll(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/domain/InvalidDummmyException.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | public class InvalidDummmyException extends RuntimeException { 4 | public InvalidDummmyException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/infrastructure/controllers/DummyController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.infrastructure.controllers.forms.CreateDummyDataForm; 5 | import com.example.demo.use_cases.CreateDummyData; 6 | import com.example.demo.use_cases.GetAllDummyData; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import java.util.List; 14 | 15 | @RestController 16 | public class DummyController { 17 | 18 | private final CreateDummyData createDummyData; 19 | 20 | private final GetAllDummyData getAllDummyData; 21 | 22 | public DummyController(CreateDummyData createDummyData, GetAllDummyData getAllDummyData) { 23 | this.createDummyData = createDummyData; 24 | this.getAllDummyData = getAllDummyData; 25 | } 26 | 27 | @GetMapping(value = "/api/dummy", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 28 | public List getAllDummyData() { 29 | return getAllDummyData.getAll(); 30 | } 31 | 32 | @PostMapping(value = "/api/dummy", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 33 | public Dummy createDummyData(@RequestBody CreateDummyDataForm createDummyDataForm) { 34 | return createDummyData.create(createDummyDataForm.toDummy()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/infrastructure/controllers/SharedExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers; 2 | 3 | import com.example.demo.domain.InvalidDummmyException; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.annotation.ControllerAdvice; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseStatus; 8 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 9 | 10 | @ControllerAdvice 11 | public class SharedExceptionHandler extends ResponseEntityExceptionHandler { 12 | 13 | @ExceptionHandler({ 14 | InvalidDummmyException.class 15 | }) 16 | @ResponseStatus(HttpStatus.BAD_REQUEST) 17 | public void handleBadRequestExceptions() { 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/infrastructure/controllers/forms/CreateDummyDataForm.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers.forms; 2 | 3 | import com.example.demo.domain.Dummy; 4 | 5 | public class CreateDummyDataForm { 6 | 7 | private String value; 8 | 9 | public Dummy toDummy() { 10 | return new Dummy(value); 11 | } 12 | 13 | public String getValue() { 14 | return value; 15 | } 16 | 17 | public void setValue(String value) { 18 | this.value = value; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/infrastructure/database/repositories/DummyJpaRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.database.repositories; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.domain.DummyRepository; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | public interface DummyJpaRepository extends JpaRepository, DummyRepository { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/use_cases/CreateDummyData.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.use_cases; 2 | 3 | 4 | import com.example.demo.domain.Dummy; 5 | import com.example.demo.domain.DummyRepository; 6 | import org.springframework.stereotype.Service; 7 | 8 | import javax.transaction.Transactional; 9 | 10 | @Service 11 | @Transactional 12 | public class CreateDummyData { 13 | 14 | private final DummyRepository dummyRepository; 15 | 16 | public CreateDummyData(DummyRepository dummyRepository) { 17 | this.dummyRepository = dummyRepository; 18 | } 19 | 20 | public Dummy create(Dummy dummy) { 21 | return dummyRepository.save(dummy); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/use_cases/GetAllDummyData.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.use_cases; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.domain.DummyRepository; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.transaction.Transactional; 8 | import java.util.List; 9 | 10 | @Service 11 | @Transactional 12 | public class GetAllDummyData { 13 | 14 | private final DummyRepository dummyRepository; 15 | 16 | public GetAllDummyData(DummyRepository dummyRepository) { 17 | this.dummyRepository = dummyRepository; 18 | } 19 | 20 | public List getAll() { 21 | return dummyRepository.findAll(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: ${PORT:8080} 3 | 4 | spring: 5 | datasource: 6 | url: ${DATABASE_URL:jdbc:h2:mem:clean-architecture-demo;FILE_LOCK=FILE;MODE=PostgreSQL} 7 | jpa: 8 | hibernate: 9 | ddl-auto: validate 10 | mapping-resources: 11 | - db/mappings/dummy.xml 12 | liquibase: 13 | change-log: classpath:db/changelog/db.changelog-master.xml 14 | -------------------------------------------------------------------------------- /src/main/resources/db/changelog/db.changelog-master.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/resources/db/mappings/dummy.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | com.example.demo.domain 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/domain/DummyUTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.domain; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Nested; 5 | import org.junit.jupiter.api.Test; 6 | import org.junit.jupiter.api.extension.ExtendWith; 7 | import org.mockito.junit.jupiter.MockitoExtension; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | import static org.assertj.core.api.Assertions.catchThrowable; 11 | 12 | @ExtendWith(MockitoExtension.class) 13 | class DummyUTest { 14 | 15 | private String value; 16 | 17 | @BeforeEach 18 | void setUp() { 19 | value = "some dummy value"; 20 | } 21 | 22 | @Nested 23 | class ConstructorShould { 24 | 25 | @Test 26 | void fail_when_value_is_null() { 27 | // Given 28 | value = null; 29 | 30 | // When 31 | Throwable throwable = catchThrowable(() -> new Dummy(value)); 32 | 33 | // Then 34 | assertThat(throwable).isInstanceOf(InvalidDummmyException.class) 35 | .hasMessage("value cannot be null or empty"); 36 | } 37 | 38 | @Test 39 | void fail_when_value_is_empty() { 40 | // Given 41 | value = ""; 42 | 43 | // When 44 | Throwable throwable = catchThrowable(() -> new Dummy(value)); 45 | 46 | // Then 47 | assertThat(throwable).isInstanceOf(InvalidDummmyException.class) 48 | .hasMessage("value cannot be null or empty"); 49 | } 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/infrastructure/controllers/DummyControllerITest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.use_cases.CreateDummyData; 5 | import com.example.demo.use_cases.GetAllDummyData; 6 | import org.junit.jupiter.api.Nested; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 11 | import org.springframework.boot.test.mock.mockito.MockBean; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.test.context.junit.jupiter.SpringExtension; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | import org.springframework.test.web.servlet.ResultActions; 16 | 17 | import static java.util.Arrays.asList; 18 | import static org.mockito.ArgumentMatchers.any; 19 | import static org.mockito.Mockito.when; 20 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 24 | 25 | @ExtendWith(SpringExtension.class) 26 | @WebMvcTest(DummyController.class) 27 | class DummyControllerITest { 28 | 29 | @Autowired 30 | private MockMvc mvc; 31 | 32 | @MockBean 33 | private CreateDummyData createDummyData; 34 | 35 | @MockBean 36 | private GetAllDummyData getAllDummyData; 37 | 38 | @Nested 39 | class GetOnApiDummyEndpointShould { 40 | 41 | @Test 42 | void return_dummy_data_as_json_array() throws Exception { 43 | // Given 44 | Dummy dummy = new Dummy("value1"); 45 | dummy.setId(42L); 46 | when(getAllDummyData.getAll()).thenReturn(asList(dummy)); 47 | 48 | // When 49 | ResultActions resultActions = mvc.perform(get("/api/dummy")); 50 | 51 | // Then 52 | resultActions.andExpect(status().isOk()) 53 | .andExpect(content().string("[{\"id\":42,\"value\":\"value1\"}]")); 54 | } 55 | } 56 | 57 | @Nested 58 | class PostOnApiDummyEndpointShould { 59 | 60 | @Test 61 | void return_created_dummy_data_as_json_object() throws Exception { 62 | // Given 63 | Dummy dummy = new Dummy("value1"); 64 | dummy.setId(1337L); 65 | when(createDummyData.create(any(Dummy.class))).thenReturn(dummy); 66 | 67 | // When 68 | ResultActions resultActions = mvc.perform(post("/api/dummy") 69 | .contentType(MediaType.APPLICATION_JSON) 70 | .content("{\"value\":\"value1\"}}")); 71 | 72 | // Then 73 | resultActions.andExpect(status().isOk()) 74 | .andExpect(content().string("{\"id\":1337,\"value\":\"value1\"}")); 75 | } 76 | 77 | @Test 78 | void return_bad_request_when_dummy_is_invalid() throws Exception { 79 | // When 80 | ResultActions resultActions = mvc.perform(post("/api/dummy") 81 | .contentType(MediaType.APPLICATION_JSON) 82 | .content("{\"value\":\"\"}}")); 83 | 84 | // Then 85 | resultActions.andExpect(status().isBadRequest()); 86 | } 87 | } 88 | 89 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/infrastructure/controllers/DummyControllerUTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.infrastructure.controllers.forms.CreateDummyDataForm; 5 | import com.example.demo.use_cases.CreateDummyData; 6 | import com.example.demo.use_cases.GetAllDummyData; 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Nested; 9 | import org.junit.jupiter.api.Test; 10 | import org.junit.jupiter.api.extension.ExtendWith; 11 | import org.mockito.ArgumentCaptor; 12 | import org.mockito.Mock; 13 | import org.mockito.junit.jupiter.MockitoExtension; 14 | 15 | import java.util.List; 16 | 17 | import static java.util.Arrays.asList; 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.mockito.ArgumentMatchers.any; 20 | import static org.mockito.Mockito.verify; 21 | import static org.mockito.Mockito.when; 22 | 23 | @ExtendWith(MockitoExtension.class) 24 | class DummyControllerUTest { 25 | 26 | private DummyController dummyController; 27 | 28 | @Mock 29 | private CreateDummyData createDummyData; 30 | 31 | @Mock 32 | private GetAllDummyData getAllDummyData; 33 | 34 | @BeforeEach 35 | void setUp() { 36 | dummyController = new DummyController(createDummyData, getAllDummyData); 37 | } 38 | 39 | @Nested 40 | class GetAllDummyDataShould { 41 | 42 | @Test 43 | void return_dummy_data() { 44 | // Given 45 | List dummyData = asList(new Dummy()); 46 | when(getAllDummyData.getAll()).thenReturn(dummyData); 47 | 48 | // When 49 | List result = dummyController.getAllDummyData(); 50 | 51 | // Then 52 | assertThat(result).isEqualTo(dummyData); 53 | } 54 | } 55 | 56 | @Nested 57 | class CreateDummyDataShould { 58 | 59 | @Test 60 | void create_dummy_using_form_value() { 61 | // Given 62 | String formValue = "some dummy value"; 63 | CreateDummyDataForm createDummyDataForm = new CreateDummyDataForm(); 64 | createDummyDataForm.setValue(formValue); 65 | 66 | // When 67 | dummyController.createDummyData(createDummyDataForm); 68 | 69 | // Then 70 | ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Dummy.class); 71 | verify(createDummyData).create(argumentCaptor.capture()); 72 | Dummy dummyToCreate = argumentCaptor.getValue(); 73 | assertThat(dummyToCreate.getValue()).isEqualTo(formValue); 74 | } 75 | 76 | @Test 77 | void return_created_dummy_data() { 78 | // Given 79 | Dummy dummy = new Dummy(); 80 | CreateDummyDataForm createDummyDataForm = new CreateDummyDataForm(); 81 | createDummyDataForm.setValue("some dummy value"); 82 | when(createDummyData.create(any(Dummy.class))).thenReturn(dummy); 83 | 84 | // When 85 | Dummy result = dummyController.createDummyData(createDummyDataForm); 86 | 87 | // Then 88 | assertThat(result).isEqualTo(dummy); 89 | } 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/infrastructure/controllers/forms/CreateDummyDataFormUTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.controllers.forms; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import org.junit.jupiter.api.Nested; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | class CreateDummyDataFormUTest { 10 | 11 | @Nested 12 | class ToDummyShould { 13 | 14 | @Test 15 | void return_new_Dummy_object_with_form_value() { 16 | // Given 17 | String formValue = "some value"; 18 | CreateDummyDataForm createDummyDataForm = new CreateDummyDataForm(); 19 | createDummyDataForm.setValue(formValue); 20 | 21 | // When 22 | Dummy dummy = createDummyDataForm.toDummy(); 23 | 24 | // Then 25 | assertThat(dummy.getValue()).isEqualTo(formValue); 26 | } 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/infrastructure/database/repositories/DummyJpaRepositoryITest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.infrastructure.database.repositories; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.domain.DummyRepository; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 11 | import org.springframework.dao.DataIntegrityViolationException; 12 | import org.springframework.test.context.junit.jupiter.SpringExtension; 13 | 14 | import java.util.List; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | import static org.assertj.core.api.Assertions.catchThrowable; 18 | 19 | @ExtendWith(SpringExtension.class) 20 | @DataJpaTest 21 | class DummyJpaRepositoryITest { 22 | 23 | @Autowired 24 | private DummyRepository dummyRepository; 25 | 26 | @Autowired 27 | private TestEntityManager testEntityManager; 28 | 29 | private Dummy dummy; 30 | 31 | @BeforeEach 32 | void setUp() { 33 | dummy = new Dummy("dummy"); 34 | } 35 | 36 | @Test 37 | void save_should_persist_dummy_with_auto_incremented_id() { 38 | // Given 39 | Dummy secondDummy = new Dummy("secondDummy"); 40 | Dummy firstPersist = dummyRepository.save(dummy); 41 | 42 | // When 43 | Dummy secondPersist = dummyRepository.save(secondDummy); 44 | 45 | // Then 46 | assertThat(secondPersist.getId()).isEqualTo(firstPersist.getId() + 1); 47 | } 48 | 49 | @Test 50 | void save_should_throw_DataIntegrityViolationException_when_value_is_null() { 51 | // Given 52 | dummy.setValue(null); 53 | 54 | // When 55 | Throwable throwable = catchThrowable(() -> dummyRepository.save(dummy)); 56 | 57 | // Then 58 | assertThat(throwable).isInstanceOf(DataIntegrityViolationException.class); 59 | assertThat(throwable).hasStackTraceContaining("value"); 60 | } 61 | 62 | @Test 63 | void findAllByUserId_should_return_all_dummy() { 64 | // Given 65 | Dummy secondDummy = new Dummy("secondDummy"); 66 | testEntityManager.persist(dummy); 67 | testEntityManager.persist(secondDummy); 68 | 69 | // When 70 | List found = dummyRepository.findAll(); 71 | 72 | // Then 73 | assertThat(found).containsExactly(dummy, secondDummy); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/use_cases/CreateDummyDataUTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.use_cases; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.domain.DummyRepository; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Nested; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.mockito.Mock; 10 | import org.mockito.junit.jupiter.MockitoExtension; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.mockito.Mockito.when; 14 | 15 | @ExtendWith(MockitoExtension.class) 16 | class CreateDummyDataUTest { 17 | 18 | private CreateDummyData createDummyData; 19 | 20 | @Mock 21 | private DummyRepository dummyRepository; 22 | 23 | @BeforeEach 24 | void setUp() { 25 | createDummyData = new CreateDummyData(dummyRepository); 26 | } 27 | 28 | @Nested 29 | class CreateShould { 30 | 31 | @Test 32 | void return_save_and_return_saved_dummy_data() { 33 | // Given 34 | Dummy dummy = new Dummy("some dummy value"); 35 | dummy.setId(42L); 36 | when(dummyRepository.save(dummy)).thenReturn(dummy); 37 | 38 | // When 39 | Dummy result = createDummyData.create(dummy); 40 | 41 | // Then 42 | assertThat(result).isEqualTo(dummy); 43 | } 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/use_cases/GetAllDummyDataUTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.use_cases; 2 | 3 | import com.example.demo.domain.Dummy; 4 | import com.example.demo.domain.DummyRepository; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Nested; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.mockito.Mock; 10 | import org.mockito.junit.jupiter.MockitoExtension; 11 | 12 | import java.util.List; 13 | 14 | import static java.util.Arrays.asList; 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.mockito.Mockito.when; 17 | 18 | @ExtendWith(MockitoExtension.class) 19 | class GetAllDummyDataUTest { 20 | 21 | private GetAllDummyData getAllDummyData; 22 | 23 | @Mock 24 | private DummyRepository dummyRepository; 25 | 26 | @BeforeEach 27 | void setUp() { 28 | getAllDummyData = new GetAllDummyData(dummyRepository); 29 | } 30 | 31 | @Nested 32 | class GetAllShould { 33 | 34 | @Test 35 | void return_all_dummy_data() { 36 | // Given 37 | List dummyData = asList(new Dummy(), new Dummy()); 38 | when(dummyRepository.findAll()).thenReturn(dummyData); 39 | 40 | // When 41 | List result = getAllDummyData.getAll(); 42 | 43 | // Then 44 | assertThat(result).isEqualTo(dummyData); 45 | } 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /tools/check-clean-architecture.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | readonly SRC_PATH="src/main/java/com/example/demo" 4 | 5 | readonly DOMAIN_PACKAGE_PATH="${SRC_PATH}/domain" 6 | readonly USE_CASES_PACKAGE_PATH="${SRC_PATH}/use_cases" 7 | 8 | readonly UNAUTHORIZED_PACKAGES_USAGE_IN_USE_CASES="infrastructure|hibernate" 9 | readonly UNAUTHORIZED_PACKAGES_USAGE_IN_DOMAIN="${UNAUTHORIZED_PACKAGES_USAGE_IN_USE_CASES}|use_cases|springframework|javax" 10 | 11 | readonly UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_DOMAIN=$(find ${DOMAIN_PACKAGE_PATH} -name "*.java" -exec egrep -w ${UNAUTHORIZED_PACKAGES_USAGE_IN_DOMAIN} {} \; | wc -l) 12 | readonly UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_USE_CASES=$(find ${USE_CASES_PACKAGE_PATH} -name "*.java" -exec egrep -w ${UNAUTHORIZED_PACKAGES_USAGE_IN_USE_CASES} {} \; | wc -l) 13 | 14 | if [[ "${UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_DOMAIN}" -eq 0 ]] && [[ "${UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_USE_CASES}" -eq 0 ]]; then 15 | exit 0 16 | fi 17 | 18 | echo "${UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_DOMAIN} unauthorized packages in ${DOMAIN_PACKAGE_PATH}:" 19 | find ${DOMAIN_PACKAGE_PATH} -name "*.java" -exec egrep -lw ${UNAUTHORIZED_PACKAGES_USAGE_IN_DOMAIN} {} \; 20 | echo "" 21 | echo "${UNAUTHORIZED_PACKAGES_USAGE_COUNT_IN_USE_CASES} unauthorized packages in ${USE_CASES_PACKAGE_PATH}:" 22 | find ${USE_CASES_PACKAGE_PATH} -name "*.java" -exec egrep -lw ${UNAUTHORIZED_PACKAGES_USAGE_IN_USE_CASES} {} \; 23 | exit 1 24 | --------------------------------------------------------------------------------