├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── info │ │ └── novatec │ │ └── axon │ │ ├── AccountApi.java │ │ ├── BankingApplication.java │ │ ├── BaseCommand.java │ │ ├── BaseEvent.java │ │ ├── account │ │ ├── BankAccount.java │ │ ├── command │ │ │ ├── CloseAccountCommand.java │ │ │ ├── CreateAccountCommand.java │ │ │ ├── DepositMoneyCommand.java │ │ │ └── WithdrawMoneyCommand.java │ │ └── event │ │ │ ├── AccountClosedEvent.java │ │ │ ├── AccountCreatedEvent.java │ │ │ ├── MoneyDepositedEvent.java │ │ │ └── MoneyWithdrawnEvent.java │ │ └── config │ │ └── AggregateConfig.java └── resources │ └── application.properties └── test └── java └── info └── novatec └── axon └── account └── BankAccountTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | 3 | # Compiled class file 4 | *.class 5 | 6 | # Log file 7 | *.log 8 | 9 | # BlueJ files 10 | *.ctxt 11 | 12 | # Mobile Tools for Java (J2ME) 13 | .mtj.tmp/ 14 | 15 | # Package Files # 16 | *.jar 17 | *.war 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | ## IntelliJ IDEA ### 24 | .idea 25 | *.iws 26 | *.iml 27 | *.ipr 28 | 29 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 30 | hs_err_pid* 31 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jd1/spring-boot-axon/829d1d64651438e72842f6409f299d6cf8068556/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-axon 2 | Event Sourcing with Spring Boot and Axon. 3 | This is the source code for a series of blog posts: 4 | 5 | * [Event Sourcing with Spring Boot and Axon](https://blog.novatec-gmbh.de/event-sourcing-spring-boot-axon/): 6 | The code for this post is tagged as [v1](https://github.com/jd1/spring-boot-axon/releases/tag/v1). 7 | 8 | * [Testing event sourcing applications with Axon](https://blog.novatec-gmbh.de/testing-event-sourcing-applications): 9 | The code for this post is tagged as [v2](https://github.com/jd1/spring-boot-axon/releases/tag/v2) 10 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # 58 | # Look for the Apple JDKs first to preserve the existing behaviour, and then look 59 | # for the new JDKs provided by Oracle. 60 | # 61 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then 62 | # 63 | # Apple JDKs 64 | # 65 | export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home 66 | fi 67 | 68 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then 69 | # 70 | # Apple JDKs 71 | # 72 | export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 73 | fi 74 | 75 | if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then 76 | # 77 | # Oracle JDKs 78 | # 79 | export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 80 | fi 81 | 82 | if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then 83 | # 84 | # Apple JDKs 85 | # 86 | export JAVA_HOME=`/usr/libexec/java_home` 87 | fi 88 | ;; 89 | esac 90 | 91 | if [ -z "$JAVA_HOME" ] ; then 92 | if [ -r /etc/gentoo-release ] ; then 93 | JAVA_HOME=`java-config --jre-home` 94 | fi 95 | fi 96 | 97 | if [ -z "$M2_HOME" ] ; then 98 | ## resolve links - $0 may be a link to maven's home 99 | PRG="$0" 100 | 101 | # need this for relative symlinks 102 | while [ -h "$PRG" ] ; do 103 | ls=`ls -ld "$PRG"` 104 | link=`expr "$ls" : '.*-> \(.*\)$'` 105 | if expr "$link" : '/.*' > /dev/null; then 106 | PRG="$link" 107 | else 108 | PRG="`dirname "$PRG"`/$link" 109 | fi 110 | done 111 | 112 | saveddir=`pwd` 113 | 114 | M2_HOME=`dirname "$PRG"`/.. 115 | 116 | # make it fully qualified 117 | M2_HOME=`cd "$M2_HOME" && pwd` 118 | 119 | cd "$saveddir" 120 | # echo Using m2 at $M2_HOME 121 | fi 122 | 123 | # For Cygwin, ensure paths are in UNIX format before anything is touched 124 | if $cygwin ; then 125 | [ -n "$M2_HOME" ] && 126 | M2_HOME=`cygpath --unix "$M2_HOME"` 127 | [ -n "$JAVA_HOME" ] && 128 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 129 | [ -n "$CLASSPATH" ] && 130 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 131 | fi 132 | 133 | # For Migwn, ensure paths are in UNIX format before anything is touched 134 | if $mingw ; then 135 | [ -n "$M2_HOME" ] && 136 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 137 | [ -n "$JAVA_HOME" ] && 138 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 139 | # TODO classpath? 140 | fi 141 | 142 | if [ -z "$JAVA_HOME" ]; then 143 | javaExecutable="`which javac`" 144 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 145 | # readlink(1) is not available as standard on Solaris 10. 146 | readLink=`which readlink` 147 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 148 | if $darwin ; then 149 | javaHome="`dirname \"$javaExecutable\"`" 150 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 151 | else 152 | javaExecutable="`readlink -f \"$javaExecutable\"`" 153 | fi 154 | javaHome="`dirname \"$javaExecutable\"`" 155 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 156 | JAVA_HOME="$javaHome" 157 | export JAVA_HOME 158 | fi 159 | fi 160 | fi 161 | 162 | if [ -z "$JAVACMD" ] ; then 163 | if [ -n "$JAVA_HOME" ] ; then 164 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 165 | # IBM's JDK on AIX uses strange locations for the executables 166 | JAVACMD="$JAVA_HOME/jre/sh/java" 167 | else 168 | JAVACMD="$JAVA_HOME/bin/java" 169 | fi 170 | else 171 | JAVACMD="`which java`" 172 | fi 173 | fi 174 | 175 | if [ ! -x "$JAVACMD" ] ; then 176 | echo "Error: JAVA_HOME is not defined correctly." >&2 177 | echo " We cannot execute $JAVACMD" >&2 178 | exit 1 179 | fi 180 | 181 | if [ -z "$JAVA_HOME" ] ; then 182 | echo "Warning: JAVA_HOME environment variable is not set." 183 | fi 184 | 185 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 186 | 187 | # For Cygwin, switch paths to Windows format before running java 188 | if $cygwin; then 189 | [ -n "$M2_HOME" ] && 190 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 191 | [ -n "$JAVA_HOME" ] && 192 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 193 | [ -n "$CLASSPATH" ] && 194 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 195 | fi 196 | 197 | # traverses directory structure from process work directory to filesystem root 198 | # first directory with .mvn subdirectory is considered project base directory 199 | find_maven_basedir() { 200 | local basedir=$(pwd) 201 | local wdir=$(pwd) 202 | while [ "$wdir" != '/' ] ; do 203 | if [ -d "$wdir"/.mvn ] ; then 204 | basedir=$wdir 205 | break 206 | fi 207 | wdir=$(cd "$wdir/.."; pwd) 208 | done 209 | echo "${basedir}" 210 | } 211 | 212 | # concatenates all lines of a file 213 | concat_lines() { 214 | if [ -f "$1" ]; then 215 | echo "$(tr -s '\n' ' ' < "$1")" 216 | fi 217 | } 218 | 219 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 220 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 221 | 222 | # Provide a "standardized" way to retrieve the CLI args that will 223 | # work with both Windows and non-Windows executions. 224 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 225 | export MAVEN_CMD_LINE_ARGS 226 | 227 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 228 | 229 | exec "$JAVACMD" \ 230 | $MAVEN_OPTS \ 231 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 232 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 233 | ${WRAPPER_LAUNCHER} "$@" 234 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | set MAVEN_CMD_LINE_ARGS=%* 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% 125 | if ERRORLEVEL 1 goto error 126 | goto end 127 | 128 | :error 129 | set ERROR_CODE=1 130 | 131 | :end 132 | @endlocal & set ERROR_CODE=%ERROR_CODE% 133 | 134 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 135 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 136 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 137 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 138 | :skipRcPost 139 | 140 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 141 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 142 | 143 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 144 | 145 | exit /B %ERROR_CODE% -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | info.novatec.axon 7 | banking 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | banking 12 | Demo project for Axon 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.1.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 3.2 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-mongodb 36 | 37 | 38 | org.axonframework 39 | axon-spring-boot-starter 40 | ${axon.version} 41 | 42 | 43 | org.axonframework 44 | axon-mongo 45 | ${axon.version} 46 | 47 | 48 | org.axonframework 49 | axon-test 50 | ${axon.version} 51 | test 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-test 56 | test 57 | 58 | 59 | junit 60 | junit 61 | 62 | 63 | 64 | 65 | org.junit.jupiter 66 | junit-jupiter-engine 67 | test 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-maven-plugin 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/AccountApi.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon; 2 | 3 | import info.novatec.axon.account.BankAccount; 4 | import info.novatec.axon.account.command.CloseAccountCommand; 5 | import info.novatec.axon.account.command.CreateAccountCommand; 6 | import info.novatec.axon.account.command.DepositMoneyCommand; 7 | import info.novatec.axon.account.command.WithdrawMoneyCommand; 8 | import org.axonframework.commandhandling.gateway.CommandGateway; 9 | import org.axonframework.commandhandling.model.AggregateNotFoundException; 10 | import org.axonframework.eventsourcing.eventstore.EventStore; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.util.List; 15 | import java.util.UUID; 16 | import java.util.concurrent.CompletableFuture; 17 | import java.util.stream.Collectors; 18 | 19 | @RequestMapping("/accounts") 20 | @RestController 21 | public class AccountApi { 22 | 23 | private final CommandGateway commandGateway; 24 | 25 | private final EventStore eventStore; 26 | 27 | public AccountApi(CommandGateway commandGateway, EventStore eventStore) { 28 | this.commandGateway = commandGateway; 29 | this.eventStore = eventStore; 30 | } 31 | 32 | @GetMapping("{id}/events") 33 | public List getEvents(@PathVariable String id) { 34 | return eventStore.readEvents(id).asStream().map(s -> s.getPayload()).collect(Collectors.toList()); 35 | } 36 | 37 | @PostMapping 38 | public CompletableFuture createAccount(@RequestBody AccountOwner user) { 39 | String id = UUID.randomUUID().toString(); 40 | return commandGateway.send(new CreateAccountCommand(id, user.name)); 41 | } 42 | 43 | @PutMapping(path = "{accountId}/balance") 44 | public CompletableFuture deposit(@RequestBody double ammount, @PathVariable String accountId) { 45 | if (ammount > 0) { 46 | return commandGateway.send(new DepositMoneyCommand(accountId, ammount)); 47 | } else { 48 | return commandGateway.send(new WithdrawMoneyCommand(accountId, -ammount)); 49 | } 50 | } 51 | 52 | @DeleteMapping("{id}") 53 | public CompletableFuture delete(@PathVariable String id) { 54 | return commandGateway.send(new CloseAccountCommand(id)); 55 | } 56 | 57 | @ExceptionHandler(AggregateNotFoundException.class) 58 | @ResponseStatus(HttpStatus.NOT_FOUND) 59 | public void notFound() { 60 | } 61 | 62 | @ExceptionHandler(BankAccount.InsufficientBalanceException.class) 63 | @ResponseStatus(HttpStatus.BAD_REQUEST) 64 | public String insufficientBalance(BankAccount.InsufficientBalanceException exception) { 65 | return exception.getMessage(); 66 | } 67 | 68 | static class AccountOwner { 69 | public String name; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/BankingApplication.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BankingApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BankingApplication.class, args); 11 | } 12 | 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/BaseCommand.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon; 2 | 3 | import org.axonframework.commandhandling.TargetAggregateIdentifier; 4 | import org.springframework.util.Assert; 5 | 6 | public class BaseCommand { 7 | @TargetAggregateIdentifier 8 | public final T id; 9 | 10 | public BaseCommand(T id) { 11 | Assert.notNull(id, "Id cannot be null"); 12 | this.id = id; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/BaseEvent.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon; 2 | 3 | import org.springframework.util.Assert; 4 | 5 | public class BaseEvent { 6 | 7 | public final T id; 8 | 9 | public BaseEvent(T id) { 10 | Assert.notNull(id, "Id cannot be null"); 11 | this.id = id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/BankAccount.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account; 2 | 3 | import info.novatec.axon.account.command.CloseAccountCommand; 4 | import info.novatec.axon.account.command.CreateAccountCommand; 5 | import info.novatec.axon.account.command.DepositMoneyCommand; 6 | import info.novatec.axon.account.command.WithdrawMoneyCommand; 7 | import info.novatec.axon.account.event.AccountClosedEvent; 8 | import info.novatec.axon.account.event.AccountCreatedEvent; 9 | import info.novatec.axon.account.event.MoneyDepositedEvent; 10 | import info.novatec.axon.account.event.MoneyWithdrawnEvent; 11 | import org.axonframework.commandhandling.CommandHandler; 12 | import org.axonframework.commandhandling.model.AggregateIdentifier; 13 | import org.axonframework.commandhandling.model.AggregateLifecycle; 14 | import org.axonframework.eventsourcing.EventSourcingHandler; 15 | import org.axonframework.spring.stereotype.Aggregate; 16 | import org.springframework.util.Assert; 17 | 18 | import java.io.Serializable; 19 | 20 | import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; 21 | 22 | @Aggregate 23 | public class BankAccount implements Serializable { 24 | 25 | private static final long serialVersionUID = 1L; 26 | 27 | @AggregateIdentifier 28 | private String id; 29 | 30 | private double balance; 31 | 32 | private String owner; 33 | 34 | @CommandHandler 35 | public BankAccount(CreateAccountCommand command) { 36 | String id = command.id; 37 | String name = command.accountCreator; 38 | 39 | Assert.hasLength(id, "Missin id"); 40 | Assert.hasLength(name, "Missig account creator"); 41 | 42 | AggregateLifecycle.apply(new AccountCreatedEvent(id, name, 0)); 43 | } 44 | 45 | public BankAccount() { 46 | // constructor needed for reconstruction 47 | } 48 | 49 | @EventSourcingHandler 50 | protected void on(AccountCreatedEvent event) { 51 | this.id = event.id; 52 | this.owner = event.accountCreator; 53 | this.balance = event.balance; 54 | } 55 | 56 | @CommandHandler 57 | protected void on(CloseAccountCommand command) { 58 | apply(new AccountClosedEvent(id)); 59 | } 60 | 61 | @EventSourcingHandler 62 | protected void on(AccountClosedEvent event) { 63 | AggregateLifecycle.markDeleted(); 64 | } 65 | 66 | @CommandHandler 67 | protected void on(DepositMoneyCommand command) { 68 | double ammount = command.ammount; 69 | 70 | Assert.isTrue(ammount > 0.0, "Deposit must be a positiv number."); 71 | 72 | AggregateLifecycle.apply(new MoneyDepositedEvent(id, ammount)); 73 | } 74 | 75 | 76 | 77 | @EventSourcingHandler 78 | protected void on(MoneyDepositedEvent event) { 79 | this.balance += event.amount; 80 | } 81 | 82 | @CommandHandler 83 | protected void on(WithdrawMoneyCommand command) { 84 | double amount = command.amount; 85 | 86 | Assert.isTrue(amount > 0.0, "Withdraw must be a positiv number."); 87 | 88 | if(balance - amount < 0) { 89 | throw new InsufficientBalanceException("Insufficient balance. Trying to withdraw: " + amount + ", but current balance is: " + balance); 90 | } 91 | 92 | AggregateLifecycle.apply(new MoneyWithdrawnEvent(id, amount)); 93 | } 94 | 95 | public static class InsufficientBalanceException extends RuntimeException { 96 | InsufficientBalanceException(String message) { 97 | super(message); 98 | } 99 | } 100 | 101 | @EventSourcingHandler 102 | protected void on(MoneyWithdrawnEvent event) { 103 | this.balance -= event.amount; 104 | } 105 | 106 | public double getBalance() { 107 | return balance; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/command/CloseAccountCommand.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.command; 2 | 3 | import info.novatec.axon.BaseCommand; 4 | 5 | public class CloseAccountCommand extends BaseCommand{ 6 | 7 | public CloseAccountCommand(String id) { 8 | super(id); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/command/CreateAccountCommand.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.command; 2 | 3 | import info.novatec.axon.BaseCommand; 4 | 5 | public class CreateAccountCommand extends BaseCommand{ 6 | public final String accountCreator; 7 | 8 | public CreateAccountCommand(String id, String accountCreator) { 9 | super(id); 10 | this.accountCreator = accountCreator; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/command/DepositMoneyCommand.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.command; 2 | 3 | import info.novatec.axon.BaseCommand; 4 | 5 | public class DepositMoneyCommand extends BaseCommand { 6 | public final double ammount; 7 | 8 | public DepositMoneyCommand(String id, double ammount) { 9 | super(id); 10 | this.ammount = ammount; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/command/WithdrawMoneyCommand.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.command; 2 | 3 | import info.novatec.axon.BaseCommand; 4 | 5 | public class WithdrawMoneyCommand extends BaseCommand { 6 | public final double amount; 7 | 8 | public WithdrawMoneyCommand(String id, double amount) { 9 | super(id); 10 | this.amount = amount; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/event/AccountClosedEvent.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.event; 2 | 3 | import org.springframework.util.Assert; 4 | 5 | public class AccountClosedEvent { 6 | 7 | public final String id; 8 | 9 | public AccountClosedEvent(String id) { 10 | Assert.notNull(id, "Id cannot be null"); 11 | this.id = id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/event/AccountCreatedEvent.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.event; 2 | 3 | import info.novatec.axon.BaseEvent; 4 | 5 | public class AccountCreatedEvent extends BaseEvent { 6 | public final String accountCreator; 7 | public final double balance; 8 | 9 | public AccountCreatedEvent(String id, String accountCreator, double balance) { 10 | super(id); 11 | this.accountCreator = accountCreator; 12 | this.balance = balance; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/event/MoneyDepositedEvent.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.event; 2 | 3 | import info.novatec.axon.BaseEvent; 4 | 5 | public class MoneyDepositedEvent extends BaseEvent { 6 | public final double amount; 7 | 8 | public MoneyDepositedEvent(String id, double amount) { 9 | super(id); 10 | this.amount = amount; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/account/event/MoneyWithdrawnEvent.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account.event; 2 | 3 | import info.novatec.axon.BaseEvent; 4 | 5 | public class MoneyWithdrawnEvent extends BaseEvent { 6 | public final double amount; 7 | 8 | public MoneyWithdrawnEvent(String id, double amount) { 9 | super(id); 10 | this.amount = amount; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/info/novatec/axon/config/AggregateConfig.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.config; 2 | 3 | import com.mongodb.MongoClient; 4 | import org.axonframework.eventsourcing.eventstore.EventStorageEngine; 5 | import org.axonframework.mongo.eventsourcing.eventstore.DefaultMongoTemplate; 6 | import org.axonframework.mongo.eventsourcing.eventstore.MongoEventStorageEngine; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class AggregateConfig { 12 | @Bean 13 | public EventStorageEngine eventStore(MongoClient client) { 14 | return new MongoEventStorageEngine(new DefaultMongoTemplate(client)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=banking 2 | -------------------------------------------------------------------------------- /src/test/java/info/novatec/axon/account/BankAccountTest.java: -------------------------------------------------------------------------------- 1 | package info.novatec.axon.account; 2 | 3 | import info.novatec.axon.account.BankAccount.InsufficientBalanceException; 4 | import info.novatec.axon.account.command.CloseAccountCommand; 5 | import info.novatec.axon.account.command.CreateAccountCommand; 6 | import info.novatec.axon.account.command.DepositMoneyCommand; 7 | import info.novatec.axon.account.command.WithdrawMoneyCommand; 8 | import info.novatec.axon.account.event.AccountClosedEvent; 9 | import info.novatec.axon.account.event.AccountCreatedEvent; 10 | import info.novatec.axon.account.event.MoneyDepositedEvent; 11 | import info.novatec.axon.account.event.MoneyWithdrawnEvent; 12 | import org.axonframework.commandhandling.model.AggregateNotFoundException; 13 | import org.axonframework.eventsourcing.eventstore.EventStoreException; 14 | import org.axonframework.test.aggregate.AggregateTestFixture; 15 | import org.axonframework.test.aggregate.FixtureConfiguration; 16 | import org.junit.jupiter.api.BeforeEach; 17 | import org.junit.jupiter.api.Test; 18 | 19 | import static org.junit.jupiter.api.Assertions.assertEquals; 20 | import static org.junit.jupiter.api.Assertions.assertThrows; 21 | 22 | 23 | public class BankAccountTest { 24 | private FixtureConfiguration fixture; 25 | 26 | @BeforeEach 27 | public void setUp() { 28 | fixture = new AggregateTestFixture(BankAccount.class); 29 | } 30 | 31 | @Test 32 | public void createAccount() { 33 | fixture.given() 34 | .when(new CreateAccountCommand("id", "Max")) 35 | .expectSuccessfulHandlerExecution() 36 | .expectEvents(new AccountCreatedEvent("id", "Max", 0.0)); 37 | } 38 | 39 | @Test 40 | public void createExistingAccount() { 41 | fixture.given(new AccountCreatedEvent("id", "Max", 0.0)) 42 | .when(new CreateAccountCommand("id", "Max")) 43 | .expectException(EventStoreException.class); 44 | } 45 | 46 | @Test 47 | public void depositMoney() { 48 | fixture.given(new AccountCreatedEvent("id", "Max", 0.0)) 49 | .when(new DepositMoneyCommand("id", 12.0)) 50 | .expectSuccessfulHandlerExecution() 51 | .expectEvents(new MoneyDepositedEvent("id", 12.0)); 52 | } 53 | 54 | @Test 55 | public void depositMoneyOnInexistentAccount() { 56 | fixture.given() 57 | .when(new DepositMoneyCommand("id", 12.0)) 58 | .expectException(AggregateNotFoundException.class); 59 | } 60 | 61 | @Test 62 | public void withdrawMoney() { 63 | fixture.given(new AccountCreatedEvent("id", "Max", 0.0), 64 | new MoneyDepositedEvent("id", 10.0)) 65 | .when(new WithdrawMoneyCommand("id", 5.0)) 66 | .expectSuccessfulHandlerExecution() 67 | .expectEvents(new MoneyWithdrawnEvent("id", 5.0)); 68 | } 69 | 70 | @Test 71 | public void overdrawAccount() { 72 | fixture.given(new AccountCreatedEvent("id", "Max", 0.0), 73 | new MoneyDepositedEvent("id", 10.0)) 74 | .when(new WithdrawMoneyCommand("id", 20.0)) 75 | .expectException(InsufficientBalanceException.class); 76 | } 77 | 78 | @Test 79 | public void closeAccount() { 80 | fixture.given(new AccountCreatedEvent("id", "Max", 0.0), 81 | new MoneyDepositedEvent("id", 10.0)) 82 | .when(new CloseAccountCommand("id")) 83 | .expectSuccessfulHandlerExecution() 84 | .expectEvents(new AccountClosedEvent("id")); 85 | } 86 | 87 | @Test 88 | public void createAndDeposit() { 89 | BankAccount account = new BankAccount(); 90 | account.on(new AccountCreatedEvent("id", "Max", 0.0)); 91 | account.on(new MoneyDepositedEvent("id", 10.0)); 92 | 93 | assertEquals(10.0, account.getBalance()); 94 | } 95 | 96 | @Test 97 | public void noAggregateLifecycle() { 98 | BankAccount account = new BankAccount(); 99 | account.on(new AccountCreatedEvent("id", "Max", 0.0)); 100 | 101 | assertThrows(IllegalStateException.class, () -> account.on(new DepositMoneyCommand("id", 10.0))); 102 | } 103 | } 104 | --------------------------------------------------------------------------------