rebased
This commit is contained in:
@@ -28,6 +28,7 @@
|
||||
<module>spring-boot-deployment</module>
|
||||
<module>spring-boot-di</module>
|
||||
<module>spring-boot-camel</module>
|
||||
<module>spring-boot-ci-cd</module>
|
||||
<!-- <module>spring-boot-cli</module> --> <!-- Not a maven project -->
|
||||
<module>spring-boot-custom-starter</module>
|
||||
<module>spring-boot-crud</module>
|
||||
@@ -48,6 +49,7 @@
|
||||
<module>spring-boot-parent</module>
|
||||
<module>spring-boot-performance</module>
|
||||
<module>spring-boot-properties</module>
|
||||
<module>spring-boot-properties-2</module>
|
||||
<module>spring-boot-property-exp</module>
|
||||
<module>spring-boot-runtime</module>
|
||||
<module>spring-boot-security</module>
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright 2007-present the original author or 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
|
||||
*
|
||||
* http://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.
|
||||
*/
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
import java.nio.channels.*;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
private static final String WRAPPER_VERSION = "0.5.6";
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
|
||||
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
|
||||
String username = System.getenv("MVNW_USERNAME");
|
||||
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
|
||||
Authenticator.setDefault(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(username, password);
|
||||
}
|
||||
});
|
||||
}
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
|
||||
@@ -0,0 +1,16 @@
|
||||
language: java
|
||||
jdk:
|
||||
- openjdk11
|
||||
services:
|
||||
- docker
|
||||
|
||||
before_install:
|
||||
- echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin
|
||||
- docker pull openjdk:11-jre-slim-sid
|
||||
|
||||
script:
|
||||
- ./mvnw clean org.jacoco:jacoco-maven-plugin:prepare-agent install
|
||||
- ./mvnw heroku:deploy jib:build -P deploy-heroku,deploy-docker
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
@@ -0,0 +1,7 @@
|
||||
# Spring Boot CI/CD
|
||||
|
||||
This module contains articles about CI/CD with Spring Boot
|
||||
|
||||
## Relevant Articles
|
||||
|
||||
- [CI/CD for a Spring Boot Project](https://www.baeldung.com/spring-boot-ci-cd)
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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
|
||||
#
|
||||
# http://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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
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
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
else
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
fi
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
if $cygwin; then
|
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
|
||||
fi
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
else
|
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
|
||||
fi
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||
else
|
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||
fi
|
||||
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaClass=`cygpath --path --windows "$javaClass"`
|
||||
fi
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
|
||||
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
||||
@@ -0,0 +1,107 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-boot-ci-cd</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-boot-ci-cd</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.5</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>deploy-heroku</id>
|
||||
<properties>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.heroku.sdk</groupId>
|
||||
<artifactId>heroku-maven-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
<configuration>
|
||||
<appName>spring-boot-ci-cd</appName>
|
||||
<processTypes>
|
||||
<web>java $JAVA_OPTS -jar -Dserver.port=$PORT target/${project.build.finalName}.jar</web>
|
||||
</processTypes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>deploy-docker</id>
|
||||
<properties>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>2.2.0</version>
|
||||
<configuration>
|
||||
<to>
|
||||
<image>registry.hub.docker.com/baeldungjib/baeldung-ci-cd-process</image>
|
||||
<tags>
|
||||
<tag>${project.version}</tag>
|
||||
<tag>latest</tag>
|
||||
</tags>
|
||||
</to>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
</project>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.cicd;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CiCdApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CiCdApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
defaultSize: 5
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.cicd;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class CiCdApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,4 @@ This module contains articles about logging in Spring Boot projects with Log4j 2
|
||||
### Relevant Articles:
|
||||
- [Logging in Spring Boot](https://www.baeldung.com/spring-boot-logging)
|
||||
- [Logging to Graylog with Spring Boot](https://www.baeldung.com/graylog-with-spring-boot)
|
||||
|
||||
- [Log Groups in Spring Boot 2.1](https://www.baeldung.com/spring-boot-log-groups)
|
||||
|
||||
@@ -87,19 +87,6 @@
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jcenter-snapshots</id>
|
||||
<name>jcenter</name>
|
||||
@@ -107,27 +94,12 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<properties>
|
||||
<spring.fox.version>3.0.0-SNAPSHOT</spring.fox.version>
|
||||
<start-class>com.baeldung.swagger2boot.SpringBootSwaggerApplication</start-class>
|
||||
<!-- <start-class>com.baeldung.springbootmvc.SpringBootMvcFnApplication</start-class> -->
|
||||
<spring-boot.version>2.2.0.BUILD-SNAPSHOT</spring-boot.version>
|
||||
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
|
||||
<xstream.version>1.4.11.1</xstream.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<version>${spring-boot-starter-data-jpa.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<spring-boot.version>2.1.5.RELEASE</spring-boot.version>
|
||||
<spring-boot-starter-data-jpa.version>2.2.5.RELEASE</spring-boot-starter-data-jpa.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
## Spring Boot Properties
|
||||
|
||||
This module contains articles about Properties in Spring Boot.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
|
||||
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
|
||||
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
|
||||
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)
|
||||
- More articles: [[<-- prev]](../spring-boot-properties)
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-boot-properties-2</artifactId>
|
||||
<name>spring-boot-properties-2</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>Spring Boot Properties Module</description>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.properties.json;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackageClasses = {JsonProperties.class, CustomJsonProperties.class})
|
||||
public class ConfigPropertiesDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())
|
||||
.run();
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.properties;
|
||||
package com.baeldung.properties.json;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
+5
-4
@@ -1,12 +1,13 @@
|
||||
package com.baeldung.properties;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
package com.baeldung.properties.json;
|
||||
|
||||
import com.baeldung.properties.json.factory.JsonPropertySourceFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
|
||||
@ConfigurationProperties
|
||||
+8
-9
@@ -1,4 +1,11 @@
|
||||
package com.baeldung.properties;
|
||||
package com.baeldung.properties.json;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
@@ -10,14 +17,6 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
|
||||
private final static String CUSTOM_PREFIX = "custom.";
|
||||
+4
-5
@@ -1,14 +1,13 @@
|
||||
package com.baeldung.properties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
package com.baeldung.properties.json.factory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.support.EncodedResource;
|
||||
import org.springframework.core.io.support.PropertySourceFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
public class JsonPropertySourceFactory implements PropertySourceFactory {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.value;
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
public class ClassNotManagedBySpring {
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@PropertySource("classpath:values.properties")
|
||||
public class CollectionProvider {
|
||||
|
||||
private final List<String> values = new ArrayList<>();
|
||||
|
||||
public Collection<String> getValues() {
|
||||
return Collections.unmodifiableCollection(values);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setValues(@Value("#{'${listOfValues}'.split(',')}") List<String> values) {
|
||||
this.values.addAll(values);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.value;
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@PropertySource("classpath:values.properties")
|
||||
public class PriorityProvider {
|
||||
|
||||
private final String priority;
|
||||
|
||||
@Autowired
|
||||
public PriorityProvider(@Value("${priority:normal}") String priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
|
||||
public String getPriority() {
|
||||
return priority;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.value;
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
public class SomeBean {
|
||||
private int someValue;
|
||||
+6
-7
@@ -1,10 +1,4 @@
|
||||
package com.baeldung.value;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
@@ -13,6 +7,11 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
@PropertySource(name = "myProperties", value = "values.properties")
|
||||
public class ValuesApp {
|
||||
+8
-12
@@ -1,10 +1,6 @@
|
||||
package com.baeldung.valuewithdefaults;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
package com.baeldung.properties.value.defaults;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
@@ -12,8 +8,9 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.primitives.Ints;
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Demonstrates setting defaults for @Value annotation. Note that there are no properties
|
||||
@@ -62,14 +59,13 @@ public class ValuesWithDefaultsApp {
|
||||
Assert.isTrue(intWithDefaultValue == 42);
|
||||
|
||||
// arrays
|
||||
List<String> stringListValues = Lists.newArrayList("one", "two", "three");
|
||||
List<String> stringListValues = Arrays.asList("one", "two", "three");
|
||||
Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues));
|
||||
|
||||
List<Integer> intListValues = Lists.newArrayList(1, 2, 3);
|
||||
Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues));
|
||||
List<Integer> intListValues = Arrays.asList(1, 2, 3);
|
||||
Assert.isTrue(Arrays.asList(ArrayUtils.toObject(intArrayWithDefaults)).containsAll(intListValues));
|
||||
|
||||
// SpEL
|
||||
Assert.isTrue(spelWithDefaultValue.equals("my default system property value"));
|
||||
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.properties.yaml;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class YamlApplication implements CommandLineRunner {
|
||||
|
||||
@Autowired
|
||||
private YamlFooProperties yamlFooProperties;
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(YamlApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
System.out.println("YAML Properties " + yamlFooProperties);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.properties.yaml;
|
||||
|
||||
import com.baeldung.properties.yaml.factory.YamlPropertySourceFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yaml")
|
||||
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
|
||||
public class YamlFooProperties {
|
||||
|
||||
private String name;
|
||||
|
||||
private List<String> aliases;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getAliases() {
|
||||
return aliases;
|
||||
}
|
||||
|
||||
public void setAliases(List<String> aliases) {
|
||||
this.aliases = aliases;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "YamlFooProperties{" +
|
||||
"name='" + name + '\'' +
|
||||
", aliases=" + aliases +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.properties.yaml.factory;
|
||||
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.env.PropertiesPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.support.EncodedResource;
|
||||
import org.springframework.core.io.support.PropertySourceFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
||||
|
||||
@Override
|
||||
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
|
||||
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
||||
factory.setResources(encodedResource.getResource());
|
||||
|
||||
Properties properties = factory.getObject();
|
||||
|
||||
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
yaml:
|
||||
name: foo
|
||||
aliases:
|
||||
- abc
|
||||
- xyz
|
||||
@@ -0,0 +1,4 @@
|
||||
value.from.file=Value got from the file
|
||||
priority=high
|
||||
listOfValues=A,B,C
|
||||
valuesMap={key1:'1', key2 : '2', key3 : '3'}
|
||||
+3
-3
@@ -1,6 +1,4 @@
|
||||
package com.baeldung.properties;
|
||||
|
||||
import java.util.Arrays;
|
||||
package com.baeldung.properties.json;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
@@ -10,6 +8,8 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class)
|
||||
public class JsonPropertiesIntegrationTest {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.value;
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = CollectionProvider.class)
|
||||
public class CollectionProviderIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CollectionProvider collectionProvider;
|
||||
|
||||
@Test
|
||||
public void givenPropertyFileWhenSetterInjectionUsedThenValueInjected() {
|
||||
assertThat(collectionProvider.getValues()).contains("A", "B", "C");
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.properties.value;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = PriorityProvider.class)
|
||||
public class PriorityProviderIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private PriorityProvider priorityProvider;
|
||||
|
||||
@Test
|
||||
public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() {
|
||||
assertThat(priorityProvider.getPriority()).isEqualTo("high");
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.properties.yaml;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class YamlFooPropertiesIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private YamlFooProperties yamlFooProperties;
|
||||
|
||||
@Test
|
||||
public void whenFactoryProvidedThenYamlPropertiesInjected() {
|
||||
assertThat(yamlFooProperties.getName()).isEqualTo("foo");
|
||||
assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz");
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,9 @@ This module contains articles about Properties in Spring Boot.
|
||||
### Relevant Articles:
|
||||
- [Reloading Properties Files in Spring](https://www.baeldung.com/spring-reloading-properties)
|
||||
- [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot)
|
||||
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
|
||||
- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties)
|
||||
- [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage
|
||||
- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation)
|
||||
- [Spring YAML Configuration](https://www.baeldung.com/spring-yaml)
|
||||
- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults)
|
||||
- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class)
|
||||
- [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties)
|
||||
- [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)
|
||||
- More articles: [[more -->]](../spring-boot-properties-2)
|
||||
@@ -128,6 +128,7 @@
|
||||
<httpcore.version>4.4.11</httpcore.version>
|
||||
<resource.delimiter>@</resource.delimiter>
|
||||
<configuration-processor.version>2.2.4.RELEASE</configuration-processor.version>
|
||||
<start-class>com.baeldung.buildproperties.Application</start-class>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.configuration.processor;
|
||||
|
||||
import org.springframework.boot.context.properties.*;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.beans.factory.annotation.*;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "com.baeldung")
|
||||
public class JdbcProperties {
|
||||
|
||||
@Value("${jdbc.url:jdbc:postgresql:/localhost:5432}")
|
||||
private String jdbcUrl;
|
||||
|
||||
public String getJdbcUrl() {
|
||||
return jdbcUrl;
|
||||
}
|
||||
|
||||
public void setJdbcUrl(String jdbcUrl) {
|
||||
this.jdbcUrl = jdbcUrl;
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -6,16 +6,23 @@ import org.springframework.stereotype.*;
|
||||
@Component
|
||||
public class PropertyBeanInjection {
|
||||
|
||||
private final CustomProperties customProperties;
|
||||
private CustomProperties customProperties;
|
||||
|
||||
PropertyBeanInjection(@Autowired CustomProperties customProperties) {
|
||||
private JdbcProperties jdbcProperties;
|
||||
|
||||
PropertyBeanInjection(@Autowired CustomProperties customProperties, @Autowired JdbcProperties jdbcProperties) {
|
||||
this.customProperties = customProperties;
|
||||
this.jdbcProperties = jdbcProperties;
|
||||
}
|
||||
|
||||
String getUrl() {
|
||||
return customProperties.getUrl();
|
||||
}
|
||||
|
||||
String getJdbcUrl() {
|
||||
return jdbcProperties.getJdbcUrl();
|
||||
}
|
||||
|
||||
int getTimeoutInMilliseconds() {
|
||||
return customProperties.getTimeoutInMilliSeconds();
|
||||
}
|
||||
|
||||
+12
-9
@@ -1,33 +1,36 @@
|
||||
package com.baeldung.properties;
|
||||
package com.baeldung.configurationproperties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
|
||||
@ConfigurationProperties(prefix = "database")
|
||||
public class Database {
|
||||
|
||||
private String url;
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
String url;
|
||||
String username;
|
||||
String password;
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.configurationproperties;
|
||||
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.beans.factory.annotation.*;
|
||||
import org.springframework.context.annotation.*;
|
||||
|
||||
@Configuration
|
||||
public class DatabaseConfig {
|
||||
|
||||
@Autowired private Environment env;
|
||||
|
||||
@Bean(name="dataSource")
|
||||
public Database dataSource() {
|
||||
|
||||
Database dataSource = new Database();
|
||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||
dataSource.setUsername(env.getProperty("database.username"));
|
||||
dataSource.setPassword(env.getProperty("database.password"));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.configurationproperties;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackageClasses = {Database.class,DatabaseConfig.class})
|
||||
public class DatabaseConfigPropertiesApp{
|
||||
|
||||
public static void main(String[]args) {SpringApplication.run(DatabaseConfigPropertiesApp.class,args);}
|
||||
|
||||
}
|
||||
+4
-3
@@ -1,5 +1,7 @@
|
||||
package com.baeldung.properties;
|
||||
|
||||
import com.baeldung.buildproperties.Application;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
@@ -7,11 +9,10 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
import com.baeldung.configurationproperties.ConfigProperties;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class })
|
||||
@ComponentScan(basePackageClasses = {ConfigProperties.class, AdditionalProperties.class})
|
||||
public class ConfigPropertiesDemoApplication {
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())
|
||||
.run();
|
||||
SpringApplication.run(ConfigPropertiesDemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.properties.spring;
|
||||
|
||||
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.*;
|
||||
|
||||
@Configuration
|
||||
public class PropertyPlaceholderConfig {
|
||||
|
||||
public PropertyPlaceholderConfig(){
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public static PropertyPlaceholderConfigurer properties() {
|
||||
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
|
||||
Resource[] resources = new ClassPathResource[]{ new ClassPathResource("foo.properties") };
|
||||
ppc.setLocations( resources );
|
||||
ppc.setIgnoreUnresolvablePlaceholders( true );
|
||||
return ppc;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.properties.spring;
|
||||
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.*;
|
||||
|
||||
@Configuration
|
||||
public class PropertySourcesPlaceholderConfig{
|
||||
|
||||
public PropertySourcesPlaceholderConfig(){
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer properties(){
|
||||
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
|
||||
Resource[] resources = new ClassPathResource[]{ new ClassPathResource("foo.properties") };
|
||||
pspc.setLocations(resources);
|
||||
pspc.setIgnoreUnresolvablePlaceholders(true);
|
||||
return pspc;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,6 +3,3 @@ spring.properties.refreshDelay=1000
|
||||
spring.config.location=file:extra.properties
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
|
||||
database.url=jdbc:postgresql:/localhost:5432/instance
|
||||
database.username=foo
|
||||
database.password=bar
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:database.properties"/>
|
||||
|
||||
|
||||
<bean id="dataSource" class="com.baeldung.configurationproperties.Database">
|
||||
<property name="url" value="${jdbc.url}" />
|
||||
<property name="username" value="${database.username}" />
|
||||
<property name="password" value="${database.password}" />
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
+2
-1
@@ -7,7 +7,8 @@
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
|
||||
|
||||
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties,classpath:database.properties"/>
|
||||
|
||||
<bean id="componentInXmlUsingProperties" class="com.baeldung.properties.core.ComponentInXmlUsingProperties">
|
||||
<constructor-arg value="${key.something}"/>
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"
|
||||
>
|
||||
|
||||
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
|
||||
<property name="locations">
|
||||
<list>
|
||||
<value>classpath:foo.properties</value>
|
||||
</list>
|
||||
</property>
|
||||
<property name="ignoreUnresolvablePlaceholders" value="true"/>
|
||||
</bean>
|
||||
|
||||
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
|
||||
<property name="locations">
|
||||
<list>
|
||||
<value>classpath:foo.properties</value>
|
||||
</list>
|
||||
</property>
|
||||
<property name="ignoreUnresolvablePlaceholders" value="true"/>
|
||||
</bean>
|
||||
</beans>
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
com.baeldung.url=www.abc.test.com
|
||||
com.baeldung.jdbc.url=
|
||||
com.baeldung.timeout-in-milli-seconds=2000
|
||||
@@ -0,0 +1,4 @@
|
||||
jdbc.url=jdbc:postgresql:/localhost:5432
|
||||
database.username=foo
|
||||
database.password=bar
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
database:
|
||||
jdbc:
|
||||
url: jdbc:postresql:/localhost:5432
|
||||
username: foo
|
||||
password: bar
|
||||
secret: foo
|
||||
@@ -1,4 +0,0 @@
|
||||
value.from.file=Value got from the file
|
||||
priority=Properties file
|
||||
listOfValues=A,B,C
|
||||
valuesMap={key1:'1', key2 : '2', key3 : '3'}
|
||||
+5
@@ -15,6 +15,11 @@ class PropertyBeanInjectionUnitTest {
|
||||
@Autowired
|
||||
private PropertyBeanInjection propertyBeanInjection;
|
||||
|
||||
@Test
|
||||
void checkThatJdbcPropertiesHaveTheCorrectValueFromPropertiesFile() {
|
||||
Assertions.assertEquals("jdbc:postgresql:/localhost:5432", propertyBeanInjection.getJdbcUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkThatCustomPropertiesHaveTheCorrectValueFromPropertiesFile() {
|
||||
Assertions.assertEquals("www.abc.test.com", propertyBeanInjection.getUrl());
|
||||
|
||||
+4
-2
@@ -4,6 +4,7 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
@@ -13,8 +14,8 @@ import com.baeldung.properties.AdditionalProperties;
|
||||
import com.baeldung.properties.ConfigPropertiesDemoApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ConfigPropertiesDemoApplication.class)
|
||||
@TestPropertySource("classpath:configprops-test.properties")
|
||||
@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class})
|
||||
@TestPropertySource(locations = {"classpath:configprops-test.properties"})
|
||||
public class ConfigPropertiesIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
@@ -53,4 +54,5 @@ public class ConfigPropertiesIntegrationTest {
|
||||
Assert.assertTrue(additionalProperties.getUnit().equals("km"));
|
||||
Assert.assertTrue(additionalProperties.getMax() == 100);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+6
-4
@@ -4,26 +4,28 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.properties.ConfigPropertiesDemoApplication;
|
||||
import com.baeldung.properties.Database;
|
||||
import com.baeldung.configurationproperties.Database;
|
||||
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ConfigPropertiesDemoApplication.class)
|
||||
@TestPropertySource("classpath:application.properties")
|
||||
@SpringBootTest(classes = DatabaseConfigPropertiesApp.class)
|
||||
@TestPropertySource("classpath:database-test.properties")
|
||||
public class DatabasePropertiesIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("dataSource")
|
||||
private Database database;
|
||||
|
||||
@Test
|
||||
public void testDatabaseProperties() {
|
||||
Assert.assertNotNull(database);
|
||||
Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl());
|
||||
Assert.assertEquals("jdbc:postgresql:/localhost:5432", database.getUrl());
|
||||
Assert.assertEquals("foo", database.getUsername());
|
||||
Assert.assertEquals("bar", database.getPassword());
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.properties.multiple;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
import com.baeldung.properties.spring.PropertyPlaceholderConfig;
|
||||
import com.baeldung.properties.spring.PropertySourcesPlaceholderConfig;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringJUnitConfig({PropertyPlaceholderConfig.class, PropertySourcesPlaceholderConfig.class})
|
||||
public class MultiplePlaceholdersJavaConfigIntegrationTest {
|
||||
|
||||
@Value("${key.something}")
|
||||
private String something;
|
||||
|
||||
|
||||
@Test
|
||||
public void whenReadInjectedValues_thenGetCorrectValues() {
|
||||
assertThat(something).isEqualTo("val");
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.properties.multiple;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
@SpringJUnitConfig(locations = "classpath:configForPropertyPlaceholderBeans.xml")
|
||||
public class MultiplePlaceholdersXmlConfigIntegrationTest {
|
||||
|
||||
@Value("${foo}")
|
||||
private String something;
|
||||
|
||||
@Value("${key.something}")
|
||||
private String something2;
|
||||
|
||||
|
||||
@Test
|
||||
public void whenReadInjectedValues_thenGetCorrectValues() {
|
||||
assertThat(something).isEqualTo("bar");
|
||||
assertThat(something2).isEqualTo("val");
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -6,16 +6,19 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringJUnitConfig(locations = "classpath:configForProperties.xml")
|
||||
@SpringJUnitConfig(locations = {"classpath:configForProperties.xml", "classpath:configForDbProperties.xml"})
|
||||
public class MultiplePropertiesXmlConfigIntegrationTest {
|
||||
|
||||
@Value("${key.something}") private String something;
|
||||
|
||||
@Value("${key.something2}") private String something2;
|
||||
|
||||
@Value("${jdbc.url}") private String jdbcUrl;
|
||||
|
||||
@Test
|
||||
public void whenReadInjectedValues_thenGetCorrectValues() {
|
||||
assertThat(something).isEqualTo("val");
|
||||
assertThat(something2).isEqualTo("val2");
|
||||
assertThat(jdbcUrl).isEqualTo("jdbc:postgresql:/localhost:5432");
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -10,6 +10,8 @@ import com.baeldung.properties.basic.PropertiesWithXmlIntegrationTest;
|
||||
import com.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest;
|
||||
import com.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest;
|
||||
import com.baeldung.properties.external.ExternalPropertiesWithXmlManualTest;
|
||||
import com.baeldung.properties.multiple.MultiplePropertiesXmlConfigIntegrationTest;
|
||||
import com.baeldung.properties.multiple.MultiplePlaceholdersXmlConfigIntegrationTest;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@SuiteClasses({ //@formatter:off
|
||||
@@ -17,8 +19,8 @@ import com.baeldung.properties.external.ExternalPropertiesWithXmlManualTest;
|
||||
ExternalPropertiesWithJavaIntegrationTest.class,
|
||||
ExternalPropertiesWithMultipleXmlsIntegrationTest.class,
|
||||
ExternalPropertiesWithXmlManualTest.class,
|
||||
ExtendedPropertiesWithJavaIntegrationTest.class,
|
||||
PropertiesWithMultipleXmlsIntegrationTest.class,
|
||||
ExtendedPropertiesWithJavaIntegrationTest.class, MultiplePropertiesXmlConfigIntegrationTest.class,
|
||||
PropertiesWithMultipleXmlsIntegrationTest.class, MultiplePlaceholdersXmlConfigIntegrationTest.class
|
||||
})// @formatter:on
|
||||
public final class IntegrationTestSuite {
|
||||
//
|
||||
|
||||
@@ -3,6 +3,3 @@ spring.properties.refreshDelay=1000
|
||||
spring.config.location=file:extra.properties
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
|
||||
database.url=jdbc:postgresql:/localhost:5432/instance
|
||||
database.username=foo
|
||||
database.password=bar
|
||||
+1
@@ -1,2 +1,3 @@
|
||||
com.baeldung.url=www.abc.test.com
|
||||
com.baeldung.jdbc.url=
|
||||
com.baeldung.timeout-in-milli-seconds=2000
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
jdbc.url=jdbc:postgresql:/localhost:5432
|
||||
database.username=foo
|
||||
database.password=bar
|
||||
@@ -37,7 +37,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
@@ -53,7 +53,19 @@
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-data-rest</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- restdocs -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.restdocs</groupId>
|
||||
<artifactId>spring-restdocs-mockmvc</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.restdocs</groupId>
|
||||
<artifactId>spring-restdocs-restassured</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -62,13 +74,49 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.asciidoctor</groupId>
|
||||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||
<version>${asciidoctor-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-docs</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>process-asciidoc</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<backend>html</backend>
|
||||
<doctype>book</doctype>
|
||||
<attributes>
|
||||
<snippets>${snippetsDirectory}</snippets>
|
||||
</attributes>
|
||||
<sourceDirectory>src/main/resources/asciidocs</sourceDirectory>
|
||||
<outputDirectory>target/generated-docs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<filtering>true</filtering>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<include>application.properties</include>
|
||||
<include>data.sql</include>
|
||||
<include>schema.sql</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<hibernate.version>5.2.10.Final</hibernate.version>
|
||||
<springdoc.version>1.2.32</springdoc.version>
|
||||
<asciidoctor-plugin.version>1.5.6</asciidoctor-plugin.version>
|
||||
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
|
||||
</properties>
|
||||
|
||||
<profiles>
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.restdocopenapi;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
|
||||
@SpringBootApplication()
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
|
||||
return new OpenAPI().info(new Info().title("Foobar API")
|
||||
.version(appVersion)
|
||||
.description("This is a sample Foobar server created using springdocs - a library for OpenAPI 3 with spring boot.")
|
||||
.termsOfService("http://swagger.io/terms/")
|
||||
.license(new License().name("Apache 2.0")
|
||||
.url("http://springdoc.org")));
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.restdocopenapi;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String title;
|
||||
|
||||
@Column()
|
||||
private String body;
|
||||
|
||||
|
||||
protected Foo() {
|
||||
}
|
||||
|
||||
public Foo(long id, String title, String body) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result;
|
||||
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||
result = prime * result + ((title == null) ? 0 : title.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (id == null) {
|
||||
if (other.id != null)
|
||||
return false;
|
||||
} else if (!id.equals(other.id))
|
||||
return false;
|
||||
if (title == null) {
|
||||
if (other.title != null)
|
||||
return false;
|
||||
} else if (!title.equals(other.title))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [id=" + id + ", title=" + title + "]";
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.restdocopenapi;
|
||||
|
||||
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/foo")
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
FooRepository repository;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Foo>> getAllFoos() {
|
||||
List<Foo> fooList = (List<Foo>) repository.findAll();
|
||||
if (fooList.isEmpty()) {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
return new ResponseEntity<>(fooList, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping(value = "{id}")
|
||||
public ResponseEntity<Foo> getFooById(@PathVariable("id") Long id) {
|
||||
|
||||
Optional<Foo> foo = repository.findById(id);
|
||||
return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<Foo> addFoo(@RequestBody @Valid Foo foo) {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setLocation(linkTo(FooController.class).slash(foo.getId())
|
||||
.toUri());
|
||||
Foo savedFoo;
|
||||
try {
|
||||
savedFoo = repository.save(foo);
|
||||
} catch (Exception e) {
|
||||
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteFoo(@PathVariable("id") long id) {
|
||||
try {
|
||||
repository.deleteById(id);
|
||||
} catch (Exception e) {
|
||||
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<Foo> updateFoo(@PathVariable("id") long id, @RequestBody Foo foo) {
|
||||
boolean isFooPresent = repository.existsById(Long.valueOf(id));
|
||||
|
||||
if (!isFooPresent) {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
Foo updatedFoo = repository.save(foo);
|
||||
|
||||
return new ResponseEntity<>(updatedFoo, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.restdocopenapi;
|
||||
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface FooRepository extends PagingAndSortingRepository<Foo, Long>{
|
||||
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package com.baeldung.restdocopenapi.springdoc;
|
||||
|
||||
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.restdocopenapi.Foo;
|
||||
import com.baeldung.restdocopenapi.FooRepository;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.ArraySchema;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/foobar")
|
||||
@Tag(name = "foobar", description = "the foobar API with documentation annotations")
|
||||
public class FooBarController {
|
||||
|
||||
@Autowired
|
||||
FooRepository repository;
|
||||
|
||||
@Operation(summary = "Get all foos")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "found foos", content = {
|
||||
@Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Foo.class)))}),
|
||||
@ApiResponse(responseCode = "404", description = "No Foos found", content = @Content) })
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Foo>> getAllFoos() {
|
||||
List<Foo> fooList = (List<Foo>) repository.findAll();
|
||||
if (fooList.isEmpty()) {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
return new ResponseEntity<>(fooList, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a foo by foo id")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "found the foo", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "Foo not found", content = @Content) })
|
||||
@GetMapping(value = "{id}")
|
||||
public ResponseEntity<Foo> getFooById(@Parameter(description = "id of foo to be searched") @PathVariable("id") String id) {
|
||||
|
||||
Optional<Foo> foo = repository.findById(Long.valueOf(id));
|
||||
return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Operation(summary = "Create a foo")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "201", description = "foo created", content = { @
|
||||
Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
|
||||
@ApiResponse(responseCode = "404", description = "Bad request", content = @Content) })
|
||||
@PostMapping
|
||||
public ResponseEntity<Foo> addFoo(@Parameter(description = "foo object to be created") @RequestBody @Valid Foo foo) {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.setLocation(linkTo(FooBarController.class).slash(foo.getId()).toUri());
|
||||
Foo savedFoo;
|
||||
try {
|
||||
savedFoo = repository.save(foo);
|
||||
} catch (Exception e) {
|
||||
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete a foo")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "204", description = "foo deleted"),
|
||||
@ApiResponse(responseCode = "404", description = "Bad request", content = @Content) })
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteFoo(@Parameter(description = "id of foo to be deleted") @PathVariable("id") long id) {
|
||||
try {
|
||||
repository.deleteById(id);
|
||||
} catch (Exception e) {
|
||||
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update a foo")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "foo updated successfully", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
|
||||
@ApiResponse(responseCode = "404", description = "No Foo exists with given id", content = @Content) })
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<Foo> updateFoo(@Parameter(description = "id of foo to be updated") @PathVariable("id") long id, @RequestBody Foo foo) {
|
||||
|
||||
boolean isFooPresent = repository.existsById(Long.valueOf(id));
|
||||
|
||||
if (!isFooPresent) {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
Foo updatedFoo = repository.save(foo);
|
||||
|
||||
return new ResponseEntity<>(updatedFoo, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,9 @@ springdoc.swagger-ui.path=/swagger-ui-custom.html
|
||||
springdoc.api-docs.path=/api-docs
|
||||
|
||||
# H2 Related Configurations
|
||||
spring.datasource.url=jdbc:h2:mem:springdoc
|
||||
spring.datasource.url=jdbc:h2:mem:springdoc
|
||||
|
||||
## for com.baeldung.restdocopenapi ##
|
||||
springdoc.version=@springdoc.version@
|
||||
spring.jpa.hibernate.ddl-auto=none
|
||||
######################################
|
||||
@@ -0,0 +1,153 @@
|
||||
= RESTful Notes API Guide
|
||||
Baeldung;
|
||||
:doctype: book
|
||||
:icons: font
|
||||
:source-highlighter: highlightjs
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:sectlinks:
|
||||
|
||||
[[overview]]
|
||||
= Overview
|
||||
|
||||
[[overview-http-verbs]]
|
||||
== HTTP verbs
|
||||
|
||||
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
|
||||
use of HTTP verbs.
|
||||
|
||||
|===
|
||||
| Verb | Usage
|
||||
|
||||
| `GET`
|
||||
| Used to retrieve a resource
|
||||
|
||||
| `POST`
|
||||
| Used to create a new resource
|
||||
|
||||
| `PUT`
|
||||
| Used to update an existing resource
|
||||
|
||||
| `DELETE`
|
||||
| Used to delete an existing resource
|
||||
|===
|
||||
|
||||
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
|
||||
use of HTTP status codes.
|
||||
|
||||
|===
|
||||
| Status code | Usage
|
||||
|
||||
| `200 OK`
|
||||
| The request completed successfully
|
||||
|
||||
| `201 Created`
|
||||
| A new resource has been created successfully. The resource's URI is available from the response's
|
||||
`Location` header
|
||||
|
||||
| `204 No Content`
|
||||
| An update to an existing resource has been applied successfully
|
||||
|
||||
| `400 Bad Request`
|
||||
| The request was malformed. The response body will include an error providing further information
|
||||
|
||||
| `404 Not Found`
|
||||
| The requested resource did not exist
|
||||
|===
|
||||
|
||||
[[overview-hypermedia]]
|
||||
== Hypermedia
|
||||
|
||||
RESTful Notes uses hypermedia and resources include links to other resources in their
|
||||
responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application
|
||||
from resource to resource.
|
||||
Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should
|
||||
not create URIs themselves, instead they should use the above-described links to navigate
|
||||
|
||||
[[resources]]
|
||||
= Resources
|
||||
|
||||
[[resources-FOO]]
|
||||
== FOO REST Service
|
||||
|
||||
The FOO provides the entry point into the service.
|
||||
|
||||
[[resources-foo-get]]
|
||||
=== Accessing the foo GET
|
||||
|
||||
A `GET` request is used to access the foo read.
|
||||
|
||||
==== Request structure
|
||||
|
||||
include::{snippets}/getAFoo/http-request.adoc[]
|
||||
|
||||
==== Path Parameters
|
||||
include::{snippets}/getAFoo/path-parameters.adoc[]
|
||||
|
||||
==== Example response
|
||||
|
||||
include::{snippets}/getAFoo/http-response.adoc[]
|
||||
|
||||
==== CURL request
|
||||
|
||||
include::{snippets}/getAFoo/curl-request.adoc[]
|
||||
|
||||
[[resources-foo-post]]
|
||||
=== Accessing the foo POST
|
||||
|
||||
A `POST` request is used to access the foo create.
|
||||
|
||||
==== Request structure
|
||||
|
||||
include::{snippets}/createFoo/http-request.adoc[]
|
||||
|
||||
==== Example response
|
||||
|
||||
include::{snippets}/createFoo/http-response.adoc[]
|
||||
|
||||
==== CURL request
|
||||
|
||||
include::{snippets}/createFoo/curl-request.adoc[]
|
||||
|
||||
[[resources-foo-delete]]
|
||||
=== Accessing the foo DELETE
|
||||
|
||||
A `DELETE` request is used to access the foo delete.
|
||||
|
||||
==== Request structure
|
||||
|
||||
include::{snippets}/deleteFoo/http-request.adoc[]
|
||||
|
||||
==== Path Parameters
|
||||
include::{snippets}/deleteFoo/path-parameters.adoc[]
|
||||
|
||||
==== Example response
|
||||
|
||||
include::{snippets}/deleteFoo/http-response.adoc[]
|
||||
|
||||
==== CURL request
|
||||
|
||||
include::{snippets}/deleteFoo/curl-request.adoc[]
|
||||
|
||||
[[resources-foo-put]]
|
||||
=== Accessing the foo PUT
|
||||
|
||||
A `PUT` request is used to access the foo update.
|
||||
|
||||
==== Request structure
|
||||
|
||||
include::{snippets}/updateFoo/http-request.adoc[]
|
||||
|
||||
==== Path Parameters
|
||||
include::{snippets}/updateFoo/path-parameters.adoc[]
|
||||
|
||||
==== Example response
|
||||
|
||||
include::{snippets}/updateFoo/http-response.adoc[]
|
||||
|
||||
==== CURL request
|
||||
|
||||
include::{snippets}/updateFoo/curl-request.adoc[]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
INSERT INTO Foo(id, title, body) VALUES (1, 'Foo 1', 'Foo body 1');
|
||||
INSERT INTO Foo(id, title, body) VALUES (2, 'Foo 2', 'Foo body 2');
|
||||
INSERT INTO Foo(id, title, body) VALUES (3, 'Foo 3', 'Foo body 3');
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
DROP TABLE IF EXISTS foo;
|
||||
|
||||
CREATE TABLE foo (
|
||||
id INTEGER NOT NULL AUTO_INCREMENT,
|
||||
title VARCHAR(250) NOT NULL,
|
||||
body VARCHAR(250),
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.restdocopenapi.restdoc;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
|
||||
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
|
||||
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;
|
||||
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
|
||||
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
|
||||
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put;
|
||||
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
|
||||
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
|
||||
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
|
||||
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
|
||||
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
|
||||
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
|
||||
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
|
||||
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.util.StringUtils.collectionToDelimitedString;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.hateoas.MediaTypes;
|
||||
import org.springframework.restdocs.RestDocumentationContextProvider;
|
||||
import org.springframework.restdocs.RestDocumentationExtension;
|
||||
import org.springframework.restdocs.constraints.ConstraintDescriptions;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.restdocopenapi.Application;
|
||||
import com.baeldung.restdocopenapi.Foo;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringRestDocsUnitTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
public void setup(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
|
||||
.apply(documentationConfiguration(restDocumentation))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFoo_thenSuccessful() throws Exception {
|
||||
this.mockMvc.perform(get("/foo"))
|
||||
.andDo(print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Foo 1")))
|
||||
.andDo(document("getAllFoos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFooById_thenSuccessful() throws Exception {
|
||||
ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class);
|
||||
|
||||
this.mockMvc.perform(get("/foo/{id}", 1))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(document("getAFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()),
|
||||
pathParameters(parameterWithName("id").description("id of foo to be searched")),
|
||||
responseFields(fieldWithPath("id").description("The id of the foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
|
||||
fieldWithPath("title").description("The title of the foo"), fieldWithPath("body").description("The body of the foo"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostFoo_thenSuccessful() throws Exception {
|
||||
Map<String, Object> foo = new HashMap<>();
|
||||
foo.put("id", 4L);
|
||||
foo.put("title", "New Foo");
|
||||
foo.put("body", "Body of New Foo");
|
||||
|
||||
this.mockMvc.perform(post("/foo").contentType(MediaTypes.HAL_JSON)
|
||||
.content(this.objectMapper.writeValueAsString(foo)))
|
||||
.andExpect(status().isCreated())
|
||||
.andDo(document("createFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the foo"), fieldWithPath("title").description("The title of the foo"),
|
||||
fieldWithPath("body").description("The body of the foo"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteFoo_thenSuccessful() throws Exception {
|
||||
this.mockMvc.perform(delete("/foo/{id}", 2))
|
||||
.andExpect(status().isNoContent())
|
||||
.andDo(document("deleteFoo", pathParameters(parameterWithName("id").description("The id of the foo to delete"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdateFoo_thenSuccessful() throws Exception {
|
||||
|
||||
ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class);
|
||||
|
||||
Map<String, Object> foo = new HashMap<>();
|
||||
foo.put("title", "Updated Foo");
|
||||
foo.put("body", "Body of Updated Foo");
|
||||
|
||||
this.mockMvc.perform(put("/foo/{id}", 3).contentType(MediaTypes.HAL_JSON)
|
||||
.content(this.objectMapper.writeValueAsString(foo)))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(document("updateFoo", pathParameters(parameterWithName("id").description("The id of the foo to update")),
|
||||
responseFields(fieldWithPath("id").description("The id of the updated foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
|
||||
fieldWithPath("title").description("The title of the updated foo"), fieldWithPath("body").description("The body of the updated foo"))));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman)
|
||||
Reference in New Issue
Block a user