diff --git a/dubbo-http-sample/pom.xml b/dubbo-http-sample/pom.xml index a42a988..98960ec 100644 --- a/dubbo-http-sample/pom.xml +++ b/dubbo-http-sample/pom.xml @@ -14,6 +14,7 @@ dubbo-http-sample Demo project for Spring Boot + 1.8 diff --git a/springboot-freemarker-sample/pom.xml b/springboot-freemarker-sample/pom.xml index 42a6d6e..0353734 100644 --- a/springboot-freemarker-sample/pom.xml +++ b/springboot-freemarker-sample/pom.xml @@ -16,18 +16,18 @@ 1.8 - 0.10.3 + org.springframework.boot spring-boot-starter - - org.springframework.experimental - spring-native - ${spring-native.version} - + + + + + org.springframework.boot @@ -67,25 +67,6 @@ - - org.springframework.experimental - spring-aot-maven-plugin - ${spring-native.version} - - - test-generate - - test-generate - - - - generate - - generate - - - - diff --git a/springboot-netty-sample/.gitignore b/springboot-netty-sample/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/springboot-netty-sample/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/springboot-netty-sample/.mvn/wrapper/maven-wrapper.jar b/springboot-netty-sample/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..c1dd12f Binary files /dev/null and b/springboot-netty-sample/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-netty-sample/.mvn/wrapper/maven-wrapper.properties b/springboot-netty-sample/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d8bc321 --- /dev/null +++ b/springboot-netty-sample/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.3/apache-maven-3.8.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/springboot-netty-sample/README.md b/springboot-netty-sample/README.md new file mode 100644 index 0000000..d884eb3 --- /dev/null +++ b/springboot-netty-sample/README.md @@ -0,0 +1,314 @@ +### Netty 笔记 + +#### 1.Netty对三种I/O模式的支持 + +image-20220124110420220 + + + +##### Netty并不是只支持过NIO,但是不建议(depercate)阻塞I/O(BIO/OIO) + +- 连接数高的情况下:阻塞 -> 消耗源、效率低 + +##### Netty也不建议(depercate)使用AIO + +- AIO在Windows 下比较成熟,但是很少用来做服务器 +- Linux 常用来做服务器,但是AIO实现不够成熟 +- Linux 的AIO相比NIO的性能没有显著的提升,反而会为开发者带来高额的维护成本 + +##### Netty和JDK NIO在Linux下,都是基于epoll实现,为什么要用Netty? + +- Netty 暴露了更多的可用参数,如: + - JDK 的 NIO 默认实现是水平触发 + - Netty 是边缘触发(默认)和水平触发可以切换 +- Netty 实现的垃圾回收更少、性能更好 + + + +#### 2.Netty NIO 中的Reactor 开发模式 + +Netty 三种开发模式版本 + +BIO 下是 Thread-Per-Connection + +image-20220124112504631 + + + +***Thread-Per-Connection:对应每个连接都有1个线程处理,1个线程同时处理:读取、解码、计算、编码、发送*** + + + +NIO 下是 Reactor + +image-20220124112753682 + + + +***Reactor 多线程模式,由多个线程负责:读取、发送,由线程池负责处理:解码、计算、编码*** + +***Reactor 主从多线程模式,由单独mainReactor 单线程负责接收请求,subReactor和 Reactor 多线程模式一致*** + + + +AIO 下是 Proactor + +Reactor 是一种开发模式,模式的核心流程: + +> 注册感兴趣的事件 -> 扫描是否有感兴趣的事件发生 -> 事件发生后做出相应的处理 + + + +##### Netty下使用 NIO 示范例 + +- Reactor 单线程模式 + +```java +//线程数1 +EventLoopGroup eventGroup = new NioEventLoopGroup(1); + +ServerBootStrap serverBootStrap = new ServerBootStrap(); +serverBootStrap.group(eventGroup); +``` + +- Reactor 多线程模式 + +```java +//多线程,不传具体的线程数时,Netty会根据CPU核心数分配 +EventLoopGroup eventGroup = new NioEventLoopGroup(); + +ServerBootStrap serverBootStrap = new ServerBootStrap(); +serverBootStrap.group(serverBootStrap); +``` + +- Reactor 主从多线程模式 + +```java +// 主线程负责接收请求 acceptor,是单线程 +EventLoopGroup bossGroup = new NioEventLoopGroup(); +// 从线程负责:读取、解码、计算、编码、发送,是多线程 +EventLoopGroup workerGroup = new NioEventLoopGroup(); + +SeverBootStrap serverBootStrap = new ServerBootStrap(); +serverBootStrap.group(bossGroup, workerGroup); +``` + + + +##### Netty 支持主从 Reactor 源码分析 + +1.初始化 Main EventLoopGroup + +```java +public abstract class AbstractBootstrap, C extends Channel> implements Cloneable { + + // main Event Loop Group + volatile EventLoopGroup group; + + .... + + // 初始化 mian Event Loop Group 方法 + public B group(EventLoopGroup group) { + ObjectUtil.checkNotNull(group, "group"); + if (this.group != null) { + throw new IllegalStateException("group set already"); + } + this.group = group; + return self(); + } + + .... +} +``` + +2. 初始化 Worker EventLoopGroup + +```java +public class ServerBootstrap extends AbstractBootstrap { + + // woker Events Loop Group + private volatile EventLoopGroup childGroup; + ..... + + public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { + super.group(parentGroup); + ObjectUtil.checkNotNull(childGroup, "childGroup"); + if (this.childGroup != null) { + throw new IllegalStateException("childGroup set already"); + } + // 初始化 worker Event Loop Group 方法 + this.childGroup = childGroup; + return this; + } + + .... +} +``` + +3. MainEventLoopGroup 和 WorkerEventLoop 绑定# bind(),并实现新建和初始化 SocketChannel 绑定到 MainEventLoopGroup中 + +```java +// 绑定 地址:端口 +public ChannelFuture bind(SocketAddress localAddress) { + validate(); + return doBind(ObjectUtil.checkNotNull(localAddress, "localAddress")); +} + +// 绑定逻辑 +private ChannelFuture doBind(final SocketAddress localAddress) { + // 初始化 & 注册 MainEventLoopGroup + final ChannelFuture regFuture = initAndRegister(); + final Channel channel = regFuture.channel(); + .... +} + +// 初始化 & 注册 MainEventLoopGroup +final ChannelFuture initAndRegister() { + Channel channel = null; + try { + // 创建新的 ServerSocketChannel + channel = channelFactory.newChannel(); + // 初始化 ServerSocketChannel 中的 Handler + init(channel); + } catch (Throwable t) { + if (channel != null) { + // channel can be null if newChannel crashed (eg SocketException("too many open files")) + channel.unsafe().closeForcibly(); + // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor + return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); + } + // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor + return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t); + } + + // 将 ServerSocketChannel 注册到 MainEventLoop 中 + // 因为端口和地址 只有1个,channel只能被注册一次,所以 MainEventLoopGroup 是单线程的 + ChannelFuture regFuture = config().group().register(channel); + if (regFuture.cause() != null) { + if (channel.isRegistered()) { + channel.close(); + } else { + channel.unsafe().closeForcibly(); + } + } + ... +} + +``` + +4. WorkerEventLoopGroup 和 SocketChannel 绑定关系 + +```java +private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter { + @Override + @SuppressWarnings("unchecked") + public void channelRead(ChannelHandlerContext ctx, Object msg) { + // 每次读取都是一个 SocketChannel + final Channel child = (Channel) msg; + + child.pipeline().addLast(childHandler); + + setChannelOptions(child, childOptions, logger); + + for (Entry, Object> e: childAttrs) { + child.attr((AttributeKey) e.getKey()).set(e.getValue()); + } + + try { + // 将 SocketChannel 注册到 workerEventLoopGroup中 + childGroup.register(child).addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (!future.isSuccess()) { + forceClose(child, future.cause()); + } + } + }); + } catch (Throwable t) { + forceClose(child, t); + } + } +} +``` + + + + + +#### 3.Netty 粘包/半包解决方案 + +关于半包的主要原因: + +- 发送写入数据> 套接字缓冲区大小 +- 发送的数据大于协议 MTU(Maximum Transmission Unit,最大传输单元),必须拆包 + +image-20220124144456949 + + + + + +关于粘包的主要原因: + +- 发送方每次写入数据> 套接字缓冲区大小 +- 接收方读取套接字缓冲区不够及时 + + + +换个角度看原因: + +- 收发时:一个发送可能多次接收,多个发送可能被一次接收 +- 传输时:一个发送可能占用多个传输包,多个发送可能公用一个传输包 + + + +导致粘包/半包的根本原因: + +TCP 是流式协议,消息无边界 + +> 提醒:UDP 像邮寄的包裹,虽然一次运输多个,但每个包裹都是 "界限",一个一个签收,所以无粘包、半包问题 + + + +***解决粘包和半包的手段: 找出消息的边界*** + +- 方式一:***短连接***(不推荐) + - 手段:TCP 连接改成短连接,一个请求一个短连接,建立连接到释放连接之间的信息即为传输信息 + - 优点:简单 + - 缺点:效率低下 + +- 方式二:***固定长度***(不推荐) + - 手段:满足固定长度即可 + - 优点:简单 + - 缺点:浪费空间 + +- 方式三:***分隔符***(推荐) + - 手段:用确定分隔符切割 + - 优点:空间不浪费,也比较简单 + - 缺点:内容本身出现分隔符时需要转义,所以需要扫描内容 + +- 方式四:***固定长度字段存个内容的长度信息***(推荐+) + - 手段:先解析固定长度的字段获取长度,然后读取后续的内容 + - 优点:精确定位用户数据,内容也不用转义 + - 缺点:长度理论上是有限制,需要提前预知可能的最大长度从而定义长度占用字节数 + +- 方式五:***序列化方式***(根据场景衡量) + - 手段:每种都不同,例如JSON 可以看{} 是否应己成对 + - 优缺点:衡量实际场景,很多是对现有协议的支持 + + + +##### Netty 粘包/半包 解决方案 + +- 固定长度 + - 解码:FixedLengthFrameDecoder +- 分隔符 + - 解码:DelimiterBasedFrameDecoder +- 固定长度存个内容长度字段 + - 解码:LengthFieldBasedFrameDecoder + - 编码:LengthFieldPerpender + + + + + diff --git a/springboot-netty-sample/mvnw b/springboot-netty-sample/mvnw new file mode 100755 index 0000000..8a8fb22 --- /dev/null +++ b/springboot-netty-sample/mvnw @@ -0,0 +1,316 @@ +#!/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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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 /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + 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="`\\unset -f command; \\command -v 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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$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 \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-netty-sample/mvnw.cmd b/springboot-netty-sample/mvnw.cmd new file mode 100644 index 0000000..1d8ab01 --- /dev/null +++ b/springboot-netty-sample/mvnw.cmd @@ -0,0 +1,188 @@ +@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 https://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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" + +FOR /F "usebackq 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%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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% + +cmd /C exit /B %ERROR_CODE% diff --git a/springboot-netty-sample/pom.xml b/springboot-netty-sample/pom.xml new file mode 100644 index 0000000..d27b746 --- /dev/null +++ b/springboot-netty-sample/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.1 + + + com.example + springboot-netty-sample + 0.0.1-SNAPSHOT + springboot-netty-sample + Demo project for Spring Boot + + + 1.8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + io.netty + netty-all + 4.1.39.Final + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplication.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplication.java new file mode 100644 index 0000000..6b1ac93 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplication.java @@ -0,0 +1,13 @@ +package com.ipman.netty.springboot.sample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootNettySampleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootNettySampleApplication.class, args); + } + +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java new file mode 100644 index 0000000..6318b40 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java @@ -0,0 +1,48 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.echo + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:26 下午 + */ +public class EchoClient { + + public static void main(String[] args) { + EventLoopGroup group = new NioEventLoopGroup(); + EchoClientHandler clientHandler = new EchoClientHandler(); + try { + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline p = ch.pipeline(); + p.addLast(new LoggingHandler(LogLevel.INFO)); + p.addLast(clientHandler); + } + }); + // 连接server端 + ChannelFuture cf = b.connect("127.0.0.1", 8090).sync(); + // 等待连接关闭 + cf.channel().closeFuture().sync(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + group.shutdownGracefully(); + } + + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java new file mode 100644 index 0000000..6289138 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java @@ -0,0 +1,78 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.echo + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:26 下午 + */ +@Sharable +public class EchoClientHandler extends ChannelInboundHandlerAdapter { + + private final ByteBuf firstMsg; + + public EchoClientHandler() { + firstMsg = Unpooled.wrappedBuffer("Hello Codeing".getBytes(StandardCharsets.UTF_8)); + } + + /** + * 通道活跃时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + // 第一次传输 + ctx.writeAndFlush(firstMsg); + } + + /** + * 读取数据时 + * + * @param ctx + * @param msg + * @throws Exception + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ctx.write(msg); + } + + /** + * 读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + // 延迟3秒 + TimeUnit.SECONDS.sleep(3); + ctx.flush(); + } + + /** + * 捕获到异常时 + * + * @param ctx + * @param cause + * @throws Exception + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java new file mode 100644 index 0000000..bb03580 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java @@ -0,0 +1,52 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:09 下午 + */ +public class EchoServer { + + public static void main(String[] args) { + // 创建Server端 + EventLoopGroup workGroup = new NioEventLoopGroup(); + final EchoServerHandler serverHandler = new EchoServerHandler(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.group(workGroup) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline p = ch.pipeline(); + p.addLast(new LoggingHandler(LogLevel.INFO)); + p.addLast(serverHandler); + } + }); + // 绑定端口 + ChannelFuture f = b.bind(8090).sync(); + // 等待连接关闭 + f.channel().closeFuture().sync(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + // 关闭所有线程 + workGroup.shutdownGracefully(); + } + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java new file mode 100644 index 0000000..c58b990 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java @@ -0,0 +1,54 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:11 下午 + */ +@Sharable +public class EchoServerHandler extends ChannelInboundHandlerAdapter { + + + /** + * 读取 + * + * @param ctx + * @param msg + * @throws Exception + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ctx.write(msg); + } + + /** + * 读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + /** + * 抓住异常 + * + * @param ctx + * @param cause + * @throws Exception + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java new file mode 100644 index 0000000..dcb2d67 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java @@ -0,0 +1,55 @@ +package com.ipman.netty.springboot.sample.http; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.handler.codec.http.HttpServerExpectContinueHandler; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 10:00 下午 + */ +public class HttpServer { + + public static void main(String[] args) { + // 主从模式 + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + // HTTP 模式 + ChannelPipeline p = ch.pipeline(); + p.addLast(new HttpServerCodec()); + p.addLast(new HttpServerExpectContinueHandler()); + p.addLast(new HttpServerHandler()); + } + }); + ChannelFuture ch = b.bind(8099).sync(); + + System.out.println("Open Http Server : http://127.0.0.1:8099"); + ch.channel().closeFuture().sync(); + + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + workerGroup.shutdownGracefully(); + bossGroup.shutdownGracefully(); + } + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java new file mode 100644 index 0000000..d0e4bf8 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java @@ -0,0 +1,60 @@ +package com.ipman.netty.springboot.sample.http; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.*; + +import java.nio.charset.StandardCharsets; + +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; +import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN; + + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:50 下午 + */ +@Sharable +public class HttpServerHandler extends SimpleChannelInboundHandler { + + private static final byte[] CONTEXT = "hello coding".getBytes(StandardCharsets.UTF_8); + + /** + * 当读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { + if (msg instanceof HttpRequest) { + HttpRequest req = (HttpRequest) msg; + FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTEXT)); + response.headers() + .set(CONTENT_TYPE, TEXT_PLAIN) + .set(CONTENT_LENGTH, response.content().readableBytes()); + + ChannelFuture f = ctx.write(response); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/springboot-netty-sample/src/main/resources/application.properties b/springboot-netty-sample/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/springboot-netty-sample/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/springboot-netty-sample/src/test/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplicationTests.java b/springboot-netty-sample/src/test/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplicationTests.java new file mode 100644 index 0000000..c9f8c24 --- /dev/null +++ b/springboot-netty-sample/src/test/java/com/ipman/netty/springboot/sample/SpringbootNettySampleApplicationTests.java @@ -0,0 +1,13 @@ +package com.ipman.netty.springboot.sample; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootNettySampleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git "a/springboot-source-code-analysis/(10)XML346円226円271円345円274円217円351円205円215円347円275円256円Bean345円256円236円346円210円230円.md" "b/springboot-source-code-analysis/(10)XML346円226円271円345円274円217円351円205円215円347円275円256円Bean345円256円236円346円210円230円.md" index 29b132c..e9a14bd 100644 --- "a/springboot-source-code-analysis/(10)XML346円226円271円345円274円217円351円205円215円347円275円256円Bean345円256円236円346円210円230円.md" +++ "b/springboot-source-code-analysis/(10)XML346円226円271円345円274円217円351円205円215円347円275円256円Bean345円256円236円346円210円230円.md" @@ -53,7 +53,7 @@ public class Student { > 无参构造器xml定义 ```java - + @@ -129,7 +129,7 @@ public class Student { > 定义有参数构造器xml配置 ```java - + @@ -242,18 +242,18 @@ public class HelloService { > 静态工厂方法 和 实例工厂方法 XML 配置 ```java - + - + - + diff --git "a/springboot-source-code-analysis/(11)351円200円232円350円277円207円Java351円205円215円347円275円256円Bean347円232円204円345円207円240円347円247円215円346円226円271円345円274円217円.md" "b/springboot-source-code-analysis/(11)351円200円232円350円277円207円Java351円205円215円347円275円256円Bean347円232円204円345円207円240円347円247円215円346円226円271円345円274円217円.md" new file mode 100644 index 0000000..98ea91c --- /dev/null +++ "b/springboot-source-code-analysis/(11)351円200円232円350円277円207円Java351円205円215円347円275円256円Bean347円232円204円345円207円240円347円247円215円346円226円271円345円274円217円.md" @@ -0,0 +1,98 @@ +### 通过Java配置Bean的几种方式 + +#### 1.通过@Configuration注解注入Bean的方式 + +```java +@Configuration +public class MyBeanConfiguration { + + /** + * 通过 @Configuration注解 注入一个Bean + */ + @Bean("dog") + public Animal getDog() { + return new Dog(); + } + +} +``` + + + +#### 2.通过实现FactoryBean接口的方式注入Bean + +```java +@Component +public class MyFactoryBean implements FactoryBean { + + /** + * 返回要注入的类 + */ + @Override + public Animal getObject() throws Exception { + return new Cat(); + } + + /** + * 获取要注入类的类型 + */ + @Override + public Class getObjectType() { + return Animal.class; + } + + @Override + public boolean isSingleton() { + return FactoryBean.super.isSingleton(); + } + +} +``` + + + +#### 3.通过实现BeanDefinitionRegistryPostProcessor接口的方式注入Bean + +```java +@Component +public class MyBeanDefinitionRegistry implements BeanDefinitionRegistryPostProcessor { + + /** + * 通过BeanDefinitionRegistryPostProcessor + */ + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { + RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); + rootBeanDefinition.setBeanClass(Monkey.class); + beanDefinitionRegistry.registerBeanDefinition("monkey", rootBeanDefinition); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { + + } +} +``` + + + +#### 4.通过实现ImportBeanDefinitionRegistrar接口的方式注入Bean + +```java +public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { + + /** + * 通过ImportBeanDefinitionRegistrar注入Bean + */ + @Override + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); + rootBeanDefinition.setBeanClass(Bird.class); + registry.registerBeanDefinition("bird", rootBeanDefinition); + } +} + +``` + +> 使用时:用 @Import(MyImportBeanDefinitionRegistrar.class) 进行注入 + diff --git "a/springboot-source-code-analysis/(12)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円270円200円.md" "b/springboot-source-code-analysis/(12)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円270円200円.md" new file mode 100644 index 0000000..507ca80 --- /dev/null +++ "b/springboot-source-code-analysis/(12)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円270円200円.md" @@ -0,0 +1,276 @@ + + +### 框架Refresh方法解析一 + + + +#### 1.Refresh方法简介 + +- Bean配置读取加载入口 +- Spring框架的启动流程 + + + +#### 2.Refresh方法的执行步骤 + +image-20211017144834689 + +```java + @Override + public void refresh() throws BeansException, IllegalStateException { + synchronized (this.startupShutdownMonitor) { + // Prepare this context for refreshing. + // 准备此上下文 + prepareRefresh(); + + // Tell the subclass to refresh the internal bean factory. + // 获取BeanFacotry -> DefaultListablesBeanFacotory + ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); + + // Prepare the bean factory for use in this context. + // 准备此类上下文中使用的Bean工厂 + prepareBeanFactory(beanFactory); + + try { + // Allows post-processing of the bean factory in context subclasses. + // 允许在上下文子类中对Bean工厂进行后处理 + postProcessBeanFactory(beanFactory); + + // Invoke factory processors registered as beans in the context. + // 调用在上下文中注册为Bean的工厂处理器 + invokeBeanFactoryPostProcessors(beanFactory); + + // Register bean processors that intercept bean creation. + // 注册拦截Bean创建的Bean处理器 + registerBeanPostProcessors(beanFactory); + + // Initialize message source for this context. + // 为此上下文初始化消息源 + initMessageSource(); + + // Initialize event multicaster for this context. + // 为此上下文初始化事件广播器 + initApplicationEventMulticaster(); + + // Initialize other special beans in specific context subclasses. + // 初始化特定上下文子类中的其他特殊Bean + onRefresh(); + + // Check for listener beans and register them. + // 检查监听器,并注册 + registerListeners(); + + // Instantiate all remaining (non-lazy-init) singletons. + // 实例化所有剩余的(非延迟初始化)单例。 + finishBeanFactoryInitialization(beanFactory); + + // Last step: publish corresponding event. + // 最后一步:发布相应的事件 + finishRefresh(); + } + + catch (BeansException ex) { + if (logger.isWarnEnabled()) { + logger.warn("Exception encountered during context initialization - " + + "cancelling refresh attempt: " + ex); + } + + // Destroy already created singletons to avoid dangling resources. + // 销毁已经创建的单例以避免浪费资源 + destroyBeans(); + + // Reset 'active' flag. + // 重置active标志 + cancelRefresh(ex); + + // Propagate exception to caller. + throw ex; + } + + finally { + // Reset common introspection caches in Spring's core, since we + // might not ever need metadata for singleton beans anymore... + // 重置 Spring 核心中的常见内省缓存,因为我们可能不再需要单例 bean 的元数据... + resetCommonCaches(); + } + } + } +``` + + + +#### 3.准备上下文:prepareRefersh#方法 + +- prepareRefersh#方法简介 + - 清除本地元数据缓存 + - 准备框架上下文 + - 设置框架启动时间 + - 设置框架 active 启动状态为true + - 如果是Debug模式打印Debug日志 + - 初始化环境配置 + - 获取当前环境配置 + - 如果是Web环境,配置ServletContext 和 ServletConfig + - 检查环境配置中的必备属性是否存在 + - 如果没有早期的事件监听器,就注册应用监听器:applicationListeners + +- prepareRefresh#方法 + +```java + @Override + protected void prepareRefresh() { + // 清除元数据缓存 + this.scanner.clearCache(); + // 准备上下文 + super.prepareRefresh(); + } +``` + +- clearCache#方法 + +```java + /** + * Clear the local metadata cache, if any, removing all cached class metadata. + * 清除本地元数据缓存(如果有),删除所有缓存的类元数据。 + */ + public void clearCache() { + if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { + // Clear cache in externally provided MetadataReaderFactory; this is a no-op + // for a shared cache since it'll be cleared by the ApplicationContext. + // 清除外部提供的 MetadataReaderFactory 中的缓存;这是一个无操作用于共享缓存,因为它将被 ApplicationContext 清除。 + ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); + } + } +``` + +- super.prepareRefresh方法 + +```java + /** + * Prepare this context for refreshing, setting its startup date and + * active flag as well as performing any initialization of property sources. + * 准备此上下文以进行刷新、设置其启动日期和* active 标志以及执行属性源的任何初始化 + */ + protected void prepareRefresh() { + // Switch to active. + // 设置启动时间 + this.startupDate = System.currentTimeMillis(); + this.closed.set(false); + // 设置 active 标志状态为 true + this.active.set(true); + + // 如果当前日志状态是Debug模式的话,会打印一段话 + if (logger.isDebugEnabled()) { + if (logger.isTraceEnabled()) { + logger.trace("Refreshing " + this); + } + else { + logger.debug("Refreshing " + getDisplayName()); + } + } + + // Initialize any placeholder property sources in the context environment. + // 初始化环境配置 + initPropertySources(); + + // Validate that all properties marked as required are resolvable: + // see ConfigurablePropertyResolver#setRequiredProperties + // 检查环境属性中必备的环境数据,如果没有就 throw MissingRequiredPropertiesException 异常 + getEnvironment().validateRequiredProperties(); + + // Store pre-refresh ApplicationListeners... + // 将系统的事件监听器进行注册 + if (this.earlyApplicationListeners == null) { + this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners); + } + else { + // Reset local application listeners to pre-refresh state. + this.applicationListeners.clear(); + this.applicationListeners.addAll(this.earlyApplicationListeners); + } + + // Allow for the collection of early ApplicationEvents, + // to be published once the multicaster is available... + this.earlyApplicationEvents = new LinkedHashSet(); + } + +``` + +- initPropertySources#方法 + +```java + protected void initPropertySources() { + // 获取环境配置上下文 + ConfigurableEnvironment env = this.getEnvironment(); + // 如果当前环境是Web环境,将servletContext 和 ServletConfig 加载到环境配置上下文中 + if (env instanceof ConfigurableWebEnvironment) { + ((ConfigurableWebEnvironment)env).initPropertySources(this.servletContext, (ServletConfig)null); + } + } +``` + + + + + +#### 获取新的Bean工厂:obtainFreshBeanFacotry#方法 + +- obtainFreshBeanFacotry#方法简介 + - 设置当前上下文刷新状态为true + - 这是BeanFactory序列化ID(默认是application) + - 返回BeanFacotry + +- obtainFreshBeanFactory#方法 + +```java + /** + * Tell the subclass to refresh the internal bean factory. + * 告诉子类刷新内部 bean 工厂 + * @return the fresh BeanFactory instance + * @see #refreshBeanFactory() + * @see #getBeanFactory() + */ + protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { + // 设置上下文刷新状态和Beanfacotory的序列化ID + refreshBeanFactory(); + // 获取BeanFactory(默认是DefaultListableBeanFacotry) + return getBeanFactory(); + } + +``` + +- refreshBeanFacoty#方法 + +```java + /** + * Do nothing: We hold a single internal BeanFactory and rely on callers + * to register beans through our public methods (or the BeanFactory's). + * @see #registerBeanDefinition + */ + @Override + protected final void refreshBeanFactory() throws IllegalStateException { + // 设置当前上下文刷新状态:true + if (!this.refreshed.compareAndSet(false, true)) { + throw new IllegalStateException( + "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); + } + // 设置BeanFacotry序列化ID:默认是application + this.beanFactory.setSerializationId(getId()); + } +``` + +- getBeanFacotory#方法 + +```java +/** + * Return the single internal BeanFactory held by this context + * (as ConfigurableListableBeanFactory). + */ + @Override + public final ConfigurableListableBeanFactory getBeanFactory() { + // 返回默认的 DefaultListableBeanFacotry + return this.beanFactory; + } +``` + + + diff --git "a/springboot-source-code-analysis/(13)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円272円214円.md" "b/springboot-source-code-analysis/(13)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円272円214円.md" new file mode 100644 index 0000000..c3b2180 --- /dev/null +++ "b/springboot-source-code-analysis/(13)346円241円206円346円236円266円Refresh346円226円271円346円263円225円350円247円243円346円236円220円344円272円214円.md" @@ -0,0 +1,390 @@ +### 框架Refresh方法解析二 + + + +#### 1.配置工厂标准上下文特征:prepareBeanFacotry() + +- 作用 + - 设置beanFacotry一些属性 + - 添加后置处理器 + - 设置忽略的自动装配接口 + - 注册一些组件 + +```java + /** + * Configure the factory's standard context characteristics, + * such as the context's ClassLoader and post-processors. + * @param beanFactory the BeanFactory to configure + * 配置工厂的标准上下文特征,比如上下文的ClassLoader和post-processors + */ + protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { + // Tell the internal bean factory to use the context's class loader etc. + // 告知内部的Bean工厂,使用上下文的类加载器 + beanFactory.setBeanClassLoader(getClassLoader()); + + // 设置Bean表达式解析器 + // 默认是spring el 表达式 + beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); + + // 注册上下文enviroment配置的引用 + // 用于做属性转换 + beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); + + // Configure the bean factory with context callbacks. + // 使用上下文回调配置 Bean 工厂 + // 在工厂的 beanPostProcessor 属性中添加Bean的后置处理器,beanPostProcessor是一个ArrayList + beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); + // 在工厂的忽略依赖接口ignoreDependencyInterface列表中添加Aware系列的接口 + // 以下Aware接口由 ApplicationContextAwareProcessor 后置处理器处理 + beanFactory.ignoreDependencyInterface(EnvironmentAware.class); + beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); + beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); + beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); + beanFactory.ignoreDependencyInterface(MessageSourceAware.class); + beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); + + // BeanFactory interface not registered as resolvable type in a plain factory. + // MessageSource registered (and found for autowiring) as a bean. + // 在普通的工厂中,BeanFactory接口并没有按照resolvable类型进行注册 + // MessageSource被注册成一个Bean(并被自动注入) + + //BeanFactory.class为key,beanFactory为value放入到了beanFactory的resolvableDependencies属性中 + //resolvableDependencies是一个ConcurrentHashMap,映射依赖类型和对应的被注入的value + //这样的话BeanFactory/ApplicationContext虽然没有以bean的方式被定义在工厂中, + //但是也能够支持自动注入,因为他处于resolvableDependencies属性中 + + // 向BeanFacotry添加一些依赖,需要解析依赖的时候指向自身 + beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); + // 再将上下文的一些接口与上下文本身做映射,一一放入到resolvableDependencies中 + beanFactory.registerResolvableDependency(ResourceLoader.class, this); + beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); + beanFactory.registerResolvableDependency(ApplicationContext.class, this); + + // Register early post-processor for detecting inner beans as ApplicationListeners. + // 将用于检测内部 bean 的早期后处理器注册为 ApplicationListeners + beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); + + // Detect a LoadTimeWeaver and prepare for weaving, if found. + // 检测LoadTimeWeaver,如果有就准备织入 + if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { + // 如果有LoadTimeWeaver,加入bean后处理器 + beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); + // Set a temporary ClassLoader for type matching. + // 为匹配类型设置一个临时的ClassLoader + beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); + } + + // Register default environment beans. + // 注册默认的environment beans + if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { + //虽然XmlWebApplicationContext中持有默认实现的StandardServletEnvironment + //但是没有注册到beanFactory中,通过getEnvironment方法拿到持有的引用 + //2.注册environment单例 + beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); + } + if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { + //注册systemProperties单例 + beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); + } + if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { + ///注册systemEnvironment单例 + beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); + } + } +``` + + + +#### 2.重写BeanFactory,在BeanFactory创建后进一步设置:postProcessBeanFactory() + +- 作用是 + - 留给开发者的扩展点,通过子类重写,在BeanFactory完成创建后做进一步设置 + - 如添加WebApplicationContextServletContextAwareProcessor后置处理器,给Web环境下的Servlet作用域进行设置:Request、Session + +- postProcessBeanFacotory()方法 + +```java + protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + // 调用父类的GenericWebApplicationContext#postProcessBeanFacotory方法 + super.postProcessBeanFactory(beanFactory); + if (!ObjectUtils.isEmpty(this.basePackages)) { + this.scanner.scan(this.basePackages); + } + + if (!this.annotatedClasses.isEmpty()) { + this.reader.register(ClassUtils.toClassArray(this.annotatedClasses)); + } + + } +``` + +- 在Web环境下注册WebApplicationContextServletContextAwareProcessor后置处理器 + +```java + /** + * Register ServletContextAwareProcessor. + * @see ServletContextAwareProcessor + */ + @Override + protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + // 添加WebApplicationContextServletContextAwareProcessor后置处理器 + beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this)); + // 忽略ServletContextAware + beanFactory.ignoreDependencyInterface(ServletContextAware.class); + // 定义Web环境下的Servlet作用域,比如:Request、Session + registerWebApplicationScopes(); + } + +``` + + + + + +#### 3.调用所有注册的BeanFactoryPostProcessor的Bean + +- 作用 + + - 框架自身的BeanFactoryPostProcessor或BeanDefinitionRegistoryPostProcessor初始化Bean的定义或属性 + + - 调用BeanDefinitionRegistryPostProcessor实现向容器内添加Bean的定义 + + - ```java + // 调用时机:在BeanFactory标准初始化之后调用,这时所有的Bean定义已经保存加载到BeanFactory,但是Bean的实例还未创建 + // 作用:来定制和修改BeanFactory内容,如添加一个Bean + @Component + public class MyBeanDefinitionRegistry implements BeanDefinitionRegistryPostProcessor { + + /** + * 通过BeanDefinitionRegistryPostProcessor + */ + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { + RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); + rootBeanDefinition.setBeanClass(Monkey.class); + beanDefinitionRegistry.registerBeanDefinition("monkey", rootBeanDefinition); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { + + } + } + ``` + + - 调用BeanFacotryPostProcessor实现容器内Bean的定义添加属性 + + - ```java + // 调用时机:在BeanFactory标准初始化之后调用,这时所有的Bean定义已经保存加载到BeanFactory,但是Bean的实例还未创建 + // 作用:来定制和修改BeanFactory内容,如覆盖或添加属性 + @Component + public class MyBeanFacotoryPostProcessor implements BeanFactoryPostProcessor { + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { + // 给DemoBean添加属性 + BeanDefinition beanDemo = configurableListableBeanFactory.getBeanDefinition("demoBean"); + MutablePropertyValues propertyValues = beanDemo.getPropertyValues(); + propertyValues.addPropertyValue("name", "ipman"); + } + } + ``` + +- 步骤 + + - 步骤一 + + image-20211017195022460 + + + + - 步骤二 + + image-20211017195333372 + + + + - 步骤三 + + image-20211017195520176 + + + + - 步骤四 + + [画像:image-20211017195711612] + +- invokeBeanFacotoryPostProcessors()方法 + +```java +public static void invokeBeanFactoryPostProcessors( + ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) { + + // 保存所有调用过的PostProcessor的beanName + Set processedBeans = new HashSet(); + + if (beanFactory instanceof BeanDefinitionRegistry) { + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + // 这两个list主要用来分别收集BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor + List regularPostProcessors = new ArrayList(); + List registryProcessors = new ArrayList(); + + for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { + // 对已注册在DefaultListBeanFactory的BeanFactoryPostProcessor进行分类 + if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { + BeanDefinitionRegistryPostProcessor registryProcessor = + (BeanDefinitionRegistryPostProcessor) postProcessor; + // 已注册在DefaultListBeanFactory的BeanDefinitionRegistryPostProcessor优先级最高 + // 如果postProcessor是BeanDefinitionRegistryPostProcessor的实例 + // 执行postProcessor的postProcessBeanDefinitionRegistry + // 为什么执行完之后还要保存到List中呢? + // 因为这里只是执行完了BeanDefinitionRegistryPostProcessor的回调 + // 父类BeanFactoryPostProcessor的方法还没有进行回调 + registryProcessor.postProcessBeanDefinitionRegistry(registry); + registryProcessors.add(registryProcessor); + } + else { + // 如果不是BeanDefinitionRegistryPostProcessor的实例 + // 则是BeanFactoryPostProcessor的实例,存放在List中,后面会进行回调 + regularPostProcessors.add(postProcessor); + } + } + + // 定义了一个集合来存放当前需要执行的BeanDefinitionRegistryPostProcessor + List currentRegistryProcessors = new ArrayList(); + + // 首先执行实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor + // 这里只能获取到Spring内部注册的BeanDefinitionRegistryPostProcessor,因为到这里spring还没有去扫描Bean,获取不到我们 // 通过@Component标志的自定义的BeanDefinitionRegistryPostProcessor + // 一般默认情况下,这里只有一个beanName, + // org.springframework.context.annotation.internalConfigurationAnnotationProcessor + // 对应的BeanClass:ConfigurationClassPostProcessor + String[] postProcessorNames = + beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); + for (String ppName : postProcessorNames) { + if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { + currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); + // 保存调用过的beanName + processedBeans.add(ppName); + } + } + // 排序 + sortPostProcessors(currentRegistryProcessors, beanFactory); + // registryProcessors存放的是BeanDefinitionRegistryPostProcessor + registryProcessors.addAll(currentRegistryProcessors); + // 执行BeanDefinitionRegistryPostProcessor,一般默认情况下,只有ConfigurationClassPostProcessor + // ConfigurationClassPostProcessor的具体作用后面再讲,这里先认为它执行完扫描,并且注册BeanDefinition + invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); + // 清空临时变量,后面再使用 + currentRegistryProcessors.clear(); + + // 第二步执行实现了Ordered的BeanDefinitionRegistryPostProcessor + // 这里为什么要再一次从beanFactory中获取所有的BeanDefinitionRegistryPostProcessor,是因为上面的操作有可能注册了 + // 新的BeanDefinitionRegistryPostProcessor,所以再获取一次 + postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); + for (String ppName : postProcessorNames) { + if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { + currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); + // 保存调用过的beanName + processedBeans.add(ppName); + } + } + sortPostProcessors(currentRegistryProcessors, beanFactory); + registryProcessors.addAll(currentRegistryProcessors); + invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); + currentRegistryProcessors.clear(); + + + // 上面两步的套路是一模一样的,唯一不一样的地方是第一步执行的是实现了PriorityOrdered的 + // BeanDefinitionRegistryPostProcessor,第二步是执行的是实现了Ordered的 + // BeanDefinitionRegistryPostProcessor + + + // 最后一步,执行没有实现PriorityOrdered或者Ordered的BeanDefinitionRegistryPostProcessor + // 比较不一样的是,这里有个while循环,是因为在实现BeanDefinitionRegistryPostProcessor的方法的过程中有可能会注册新的 + // BeanDefinitionRegistryPostProcessor,所以需要处理,直到不会出现新的BeanDefinitionRegistryPostProcessor为止 + boolean reiterate = true; + while (reiterate) { + reiterate = false; + postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); + for (String ppName : postProcessorNames) { + if (!processedBeans.contains(ppName)) { + // 发现还有未处理过的BeanDefinitionRegistryPostProcessor,按照套路放进list中 + // reiterate标记为true,后面还要再执行一次这个循环,因为执行新的BeanDefinitionRegistryPostProcessor有可能会 + // 注册新的BeanDefinitionRegistryPostProcessor + currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); + processedBeans.add(ppName); + reiterate = true; + } + } + sortPostProcessors(currentRegistryProcessors, beanFactory); + registryProcessors.addAll(currentRegistryProcessors); + invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); + currentRegistryProcessors.clear(); + } + // 方法开头前几行分类的两个list就是在这里调用 + // BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor + // 刚刚执行了BeanDefinitionRegistryPostProcessor的方法 + // 现在要执行父类BeanFactoryPostProcessor的方法 + invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); + invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); + } + + else { + // Invoke factory processors registered with the context instance. + invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); + } + + + // 上面BeanFactoryPostProcessor的回调可能又注册了一些类,下面需要再走一遍之前的逻辑 + String[] postProcessorNames = + beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); + + // 根据不同的优先级,分成三类 + List priorityOrderedPostProcessors = new ArrayList(); + List orderedPostProcessorNames = new ArrayList(); + List nonOrderedPostProcessorNames = new ArrayList(); + for (String ppName : postProcessorNames) { + // 上面处理BeanDefinitionRegistryPostProcessor的时候已经处理过,这里不再重复处理 + // 因为BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor + if (processedBeans.contains(ppName)) { + // skip - already processed in first phase above + } + else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { + priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); + } + else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { + orderedPostProcessorNames.add(ppName); + } + else { + nonOrderedPostProcessorNames.add(ppName); + } + } + + // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. + // 下面的逻辑跟上面是一致的,先处理实现了PriorityOrdered接口的 + // 再处理实现了Ordered接口的 + // 最后处理普通的BeanFactoryPostProcessor + sortPostProcessors(priorityOrderedPostProcessors, beanFactory); + invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); + + // Next, invoke the BeanFactoryPostProcessors that implement Ordered. + List orderedPostProcessors = new ArrayList(); + for (String postProcessorName : orderedPostProcessorNames) { + orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); + } + sortPostProcessors(orderedPostProcessors, beanFactory); + invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); + + // Finally, invoke all other BeanFactoryPostProcessors. + List nonOrderedPostProcessors = new ArrayList(); + for (String postProcessorName : nonOrderedPostProcessorNames) { + nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); + } + invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); + + // 因为各种BeanFactoryPostProcessor可能修改了BeanDefinition + // 所以这里需要清除缓存,需要的时候再通过merge的方式获取 + beanFactory.clearMetadataCache(); +} +``` + diff --git "a/springboot-source-code-analysis/(3)345円267円245円345円216円202円345円212円240円350円275円275円346円234円272円345円210円266円350円247円243円346円236円220円.md" "b/springboot-source-code-analysis/(3)345円267円245円345円216円202円345円212円240円350円275円275円346円234円272円345円210円266円350円247円243円346円236円220円.md" index cd2d8b8..9dc5a54 100644 --- "a/springboot-source-code-analysis/(3)345円267円245円345円216円202円345円212円240円350円275円275円346円234円272円345円210円266円350円247円243円346円236円220円.md" +++ "b/springboot-source-code-analysis/(3)345円267円245円345円216円202円345円212円240円350円275円275円346円234円272円345円210円266円350円247円243円346円236円220円.md" @@ -69,7 +69,7 @@ public final class SpringFactoriesLoader { ClassLoader classLoader = getClassLoader(); // 通过这个SpringFactoriesLoader#loadFactoryNames方法获取Spring中所有系统初始化器实现的全路径名 Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); - // 通过createSpringFactoriesInstances#()创建它们的实例 + // #()创建它们的实例 List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); // 通过注解@Order进行排序 AnnotationAwareOrderComparator.sort(instances); diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/initializer/FirstInitializer.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/initializer/FirstInitializer.java index 6cc9d1d..38edbf3 100644 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/initializer/FirstInitializer.java +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/initializer/FirstInitializer.java @@ -30,6 +30,9 @@ public void initialize(ConfigurableApplicationContext configurableApplicationCon ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment(); + // 设置必填属性 + environment.setRequiredProperties("app.enviroment"); + // 设置自定义属性 Map attributeMap = new HashMap(); attributeMap.put("firstKey", "firstValue"); diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanConfiguration.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanConfiguration.java new file mode 100644 index 0000000..547e15c --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanConfiguration.java @@ -0,0 +1,27 @@ +package com.example.springboot.source.code.analysis.ioc.ann; + +import com.example.springboot.source.code.analysis.ioc.pojo.Animal; +import com.example.springboot.source.code.analysis.ioc.pojo.Dog; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.ann + * @Description: (通过 @Configuration注解 注入一个Bean) + * @date 2021年10月16日 12:04 下午 + */ +@Configuration +public class MyBeanConfiguration { + + /** + * 通过 @Configuration注解 注入一个Bean + */ + @Bean("dog") + public Animal getDog() { + return new Dog(); + } + +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanDefinitionRegistry.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanDefinitionRegistry.java new file mode 100644 index 0000000..ab84f26 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanDefinitionRegistry.java @@ -0,0 +1,37 @@ +package com.example.springboot.source.code.analysis.ioc.ann; + +import com.example.springboot.source.code.analysis.ioc.pojo.Monkey; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.ann + * @Description: (通过BeanDefinitionRegistryPostProcessor 进行Bean的注入) + * @date 2021年10月16日 3:18 下午 + */ +@Component +public class MyBeanDefinitionRegistry implements BeanDefinitionRegistryPostProcessor { + + /** + * 通过BeanDefinitionRegistryPostProcessor + */ + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { + RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); + rootBeanDefinition.setBeanClass(Monkey.class); + beanDefinitionRegistry.registerBeanDefinition("monkey", rootBeanDefinition); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { + + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanFacotoryPostProcessor.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanFacotoryPostProcessor.java new file mode 100644 index 0000000..a08d25e --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyBeanFacotoryPostProcessor.java @@ -0,0 +1,32 @@ +package com.example.springboot.source.code.analysis.ioc.ann; + +import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.stereotype.Component; + +/** + * Created by ipipman on 2021年10月17日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.ann + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月17日 6:47 下午 + */ + +// 调用时机:在BeanFactory标准初始化之后调用,这时所有的Bean定义已经保存加载到BeanFactory,但是Bean的实例还未创建 +// 作用:来定制和修改BeanFactory内容,如覆盖或添加属性 +@Component +public class MyBeanFacotoryPostProcessor implements BeanFactoryPostProcessor { + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { + // 给DemoBean添加属性 + BeanDefinition beanDemo = configurableListableBeanFactory.getBeanDefinition("demoBean"); + MutablePropertyValues propertyValues = beanDemo.getPropertyValues(); + propertyValues.addPropertyValue("name", "ipman"); + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyFactoryBean.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyFactoryBean.java new file mode 100644 index 0000000..486a909 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyFactoryBean.java @@ -0,0 +1,41 @@ +package com.example.springboot.source.code.analysis.ioc.ann; + +import com.example.springboot.source.code.analysis.ioc.pojo.Animal; +import com.example.springboot.source.code.analysis.ioc.pojo.Cat; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.stereotype.Component; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.ann + * @Description: (通过实现 FactoryBean < ?> 接口实现Bean的注入) + * @date 2021年10月16日 12:15 下午 + */ +@Component +public class MyFactoryBean implements FactoryBean { + + /** + * 返回要注入的类 + */ + @Override + public Animal getObject() throws Exception { + return new Cat(); + } + + /** + * 获取要注入类的类型 + */ + @Override + public Class getObjectType() { + return Animal.class; + } + + @Override + public boolean isSingleton() { + return FactoryBean.super.isSingleton(); + } + +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyImportBeanDefinitionRegistrar.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyImportBeanDefinitionRegistrar.java new file mode 100644 index 0000000..f04aca8 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/ann/MyImportBeanDefinitionRegistrar.java @@ -0,0 +1,28 @@ +package com.example.springboot.source.code.analysis.ioc.ann; + +import com.example.springboot.source.code.analysis.ioc.pojo.Bird; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; +import org.springframework.core.type.AnnotationMetadata; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.ann + * @Description: (通过ImportBeanDefinitionRegistrar注入Bean) + * @date 2021年10月16日 3:32 下午 + */ +public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { + + /** + * 通过ImportBeanDefinitionRegistrar注入Bean + */ + @Override + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); + rootBeanDefinition.setBeanClass(Bird.class); + registry.registerBeanDefinition("bird", rootBeanDefinition); + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Animal.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Animal.java new file mode 100644 index 0000000..74d5d78 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Animal.java @@ -0,0 +1,14 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 12:06 下午 + */ +public abstract class Animal { + + public abstract String getName(); +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Bird.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Bird.java new file mode 100644 index 0000000..e65bf5e --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Bird.java @@ -0,0 +1,16 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 3:35 下午 + */ +public class Bird extends Animal{ + @Override + public String getName() { + return "Bird"; + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Cat.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Cat.java new file mode 100644 index 0000000..79bb1ab --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Cat.java @@ -0,0 +1,16 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 12:09 下午 + */ +public class Cat extends Animal{ + @Override + public String getName() { + return "Cat"; + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/DemoBean.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/DemoBean.java new file mode 100644 index 0000000..72f65ee --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/DemoBean.java @@ -0,0 +1,27 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +import org.springframework.stereotype.Component; + +/** + * Created by ipipman on 2021年10月17日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月17日 6:53 下午 + */ +@Component +public class DemoBean { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Dog.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Dog.java new file mode 100644 index 0000000..5dcd836 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Dog.java @@ -0,0 +1,16 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 12:08 下午 + */ +public class Dog extends Animal{ + @Override + public String getName() { + return "Dog"; + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Monkey.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Monkey.java new file mode 100644 index 0000000..7e922ad --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/pojo/Monkey.java @@ -0,0 +1,16 @@ +package com.example.springboot.source.code.analysis.ioc.pojo; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.pojo + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 12:25 下午 + */ +public class Monkey extends Animal { + @Override + public String getName() { + return "Monkey"; + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/service/HelloService.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/service/HelloService.java new file mode 100644 index 0000000..ec6f7d0 --- /dev/null +++ b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/ioc/service/HelloService.java @@ -0,0 +1,37 @@ +package com.example.springboot.source.code.analysis.ioc.service; + +import com.example.springboot.source.code.analysis.ioc.pojo.Animal; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import javax.swing.event.AncestorEvent; + +/** + * Created by ipipman on 2021年10月16日. + * + * @version V1.0 + * @Package com.example.springboot.source.code.analysis.ioc.service + * @Description: (用一句话描述该文件做什么) + * @date 2021年10月16日 12:10 下午 + */ + +@Component +public class HelloService { + + /** + * animal + */ + @Autowired + // 如果有多个同类型的Bean,那么用@Qualifier指定Bean的名称后进行注入 + //@Qulifier("dog") // 通过@Configuration注解进行Bean的注入 + //@Qualifier("myFactoryBean") // 通过FacotryBean接口进行Bean的注入 + //@Qualifier("monkey") // 通过BeanDefinitionRegistryPostProcessor接口进行Bean的注入 + @Qualifier("bird") // 通过ImpoortBeanDefinitionRegistrar接口进行Bean的注入 + private Animal animal; + + + public String hello() { + return animal.getName(); + } +} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Animal.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Animal.java deleted file mode 100644 index 467c9c0..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Animal.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:34 上午 - */ -public abstract class Animal { - - abstract String getName(); -} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/AnimalFactory.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/AnimalFactory.java deleted file mode 100644 index ece42a6..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/AnimalFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:44 上午 - */ -public class AnimalFactory { - - // 静态工厂 - public static Animal getAnimal(String type) { - if ("Dog".equals(type)) { - return new Dog(); - } else { - return new Cat(); - } - } - - // 实例工厂 - public Animal getAnimal1(String type) { - if ("Dog".equals(type)) { - return new Dog(); - } else { - return new Cat(); - } - } -} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Cat.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Cat.java deleted file mode 100644 index 6c14b84..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Cat.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:43 上午 - */ -public class Cat extends Animal{ - @Override - String getName() { - return "Cat"; - } -} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Dog.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Dog.java deleted file mode 100644 index c64aabd..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Dog.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:43 上午 - */ -public class Dog extends Animal{ - @Override - String getName() { - return "Dog"; - } -} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/HelloService.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/HelloService.java deleted file mode 100644 index de920aa..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/HelloService.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:26 上午 - */ -public class HelloService { - - private Student student; - - private Animal animal; - - public Animal getAnimal() { - return animal; - } - - public void setAnimal(Animal animal) { - this.animal = animal; - } - - public Student getStudent() { - return student; - } - - public void setStudent(Student student) { - this.student = student; - } - - public String hello() { - //return student.toString(); - return animal.getName(); - } - -} diff --git a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Student.java b/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Student.java deleted file mode 100644 index 15abe3e..0000000 --- a/springboot-source-code-analysis/src/main/java/com/example/springboot/source/code/analysis/xml/Student.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.example.springboot.source.code.analysis.xml; - -import java.util.List; - -/** - * Created by ipipman on 2021年9月22日. - * - * @version V1.0 - * @Package com.example.springboot.source.code.analysis.xml - * @Description: (用一句话描述该文件做什么) - * @date 2021年9月22日 10:19 上午 - */ -public class Student { - - private String name; - private Integer age; - private List classList; - - /** - * 使用构造器注入 - * - * @param name - * @param age - */ - public Student(String name, Integer age) { - this.name = name; - this.age = age; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public List getClassList() { - return classList; - } - - public void setClassList(List classList) { - this.classList = classList; - } - - @Override - public String toString() { - return "Student{" + - "name='" + name + '\'' + - ", age=" + age + - ", classList=" + String.join(",", classList) + - '}'; - } -} diff --git a/springboot-source-code-analysis/src/main/resources/application.properties b/springboot-source-code-analysis/src/main/resources/application.properties index 82918ee..856742a 100644 --- a/springboot-source-code-analysis/src/main/resources/application.properties +++ b/springboot-source-code-analysis/src/main/resources/application.properties @@ -5,4 +5,8 @@ context.initializer.classes=\ # 通过系统事件监听器,监听事件 context.listener.classes=\ com.example.springboot.source.code.analysis.listener.ThirdListener,\ - com.example.springboot.source.code.analysis.listener.FourthListener \ No newline at end of file + com.example.springboot.source.code.analysis.listener.FourthListener + + +# 通过ConfigurableEnviroment.requiredProperty()方法设置的必填属性 +app.enviroment=ipman \ No newline at end of file diff --git a/springboot-source-code-analysis/src/main/resources/ioc/demo.xml b/springboot-source-code-analysis/src/main/resources/ioc/demo.xml deleted file mode 100644 index 21178a2..0000000 --- a/springboot-source-code-analysis/src/main/resources/ioc/demo.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - math - english - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/springboot-source-code-analysis/src/test/java/com/example/springboot/source/code/analysis/SpringbootSourceCodeAnalysisApplicationTests.java b/springboot-source-code-analysis/src/test/java/com/example/springboot/source/code/analysis/SpringbootSourceCodeAnalysisApplicationTests.java index 8e79132..b78658e 100644 --- a/springboot-source-code-analysis/src/test/java/com/example/springboot/source/code/analysis/SpringbootSourceCodeAnalysisApplicationTests.java +++ b/springboot-source-code-analysis/src/test/java/com/example/springboot/source/code/analysis/SpringbootSourceCodeAnalysisApplicationTests.java @@ -2,18 +2,23 @@ import com.example.springboot.source.code.analysis.event.RainListener; import com.example.springboot.source.code.analysis.event.WeatherRunListener; +import com.example.springboot.source.code.analysis.ioc.ann.MyImportBeanDefinitionRegistrar; +import com.example.springboot.source.code.analysis.ioc.pojo.DemoBean; +import com.example.springboot.source.code.analysis.ioc.service.HelloService; import com.example.springboot.source.code.analysis.listener.ApplicationContextContainer; -import com.example.springboot.source.code.analysis.xml.HelloService; 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.ContextConfiguration; +import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest(classes = SpringbootSourceCodeAnalysisApplication.class) @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "classpath:ioc/demo.xml") +// 通过XML注入Bean +//@ContextConfiguration(locations = "classpath:ioc/demo.xml") +// 通过ImportBeanDefinitionRegistrar进行Bean的注入 +@Import(MyImportBeanDefinitionRegistrar.class) public class SpringbootSourceCodeAnalysisApplicationTests { // 引入事件监听器 @@ -36,12 +41,12 @@ public void testContextRefreshEvent() { weatherRunListener.rain(); } - // 引入XML Bean + @Autowired - private HelloService helloService; + HelloService helloService; @Test - public void testHello(){ + public void testHello() { System.out.println(helloService.hello()); } @@ -51,4 +56,13 @@ public void contextLoads() { } + @Autowired + DemoBean demoBean; + + @Test + public void sayDemoBean(){ + System.out.println(demoBean.getName()); + } + + } diff --git a/springcloud-consul-config-sample/src/main/java/com/ipman/springcloud/consul/config/center/sample/SpringcloudConsulConfigSampleApplication.java b/springcloud-consul-config-sample/src/main/java/com/ipman/springcloud/consul/config/center/sample/SpringcloudConsulConfigSampleApplication.java index cd4c623..e833700 100644 --- a/springcloud-consul-config-sample/src/main/java/com/ipman/springcloud/consul/config/center/sample/SpringcloudConsulConfigSampleApplication.java +++ b/springcloud-consul-config-sample/src/main/java/com/ipman/springcloud/consul/config/center/sample/SpringcloudConsulConfigSampleApplication.java @@ -8,6 +8,7 @@ @EnableDiscoveryClient //让注册中心进行服务发现,将服务注册到服务组件上 public class SpringcloudConsulConfigSampleApplication { + // hello public static void main(String[] args) { SpringApplication.run(SpringcloudConsulConfigSampleApplication.class, args); }

AltStyle によって変換されたページ (->オリジナル) /