├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.MD ├── mvnw ├── mvnw.cmd ├── pom.xml ├── spring-cloud-feign-proxy-sample ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── github │ │ └── leecho │ │ └── spring │ │ └── feign │ │ └── sample │ │ ├── DemoApplication.java │ │ ├── Swagger2AutoConfiguration.java │ │ ├── model │ │ └── Demo.java │ │ └── service │ │ ├── DemoService.java │ │ └── impl │ │ └── DemoServiceImpl.java │ └── test │ └── java │ └── com │ └── github │ └── leecho │ └── spring │ └── feign │ └── sample │ └── service │ └── impl │ └── DemoApplicationTest.java └── spring-cloud-starter-feign-proxy ├── pom.xml └── src └── main └── java └── com └── github └── leecho └── spring └── cloud └── feign ├── EnableFeignProxies.java ├── FeignProxiesRegistrar.java ├── FeignProxyController.java ├── FeignProxyInvocationHandler.java └── FeignProxyMvcConfiguration.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leecho/spring-cloud-feign-proxy/f15553404aad36127b82f0a03c20602a7f52a3e8/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | This project can automatically expose FeignClients to Rest without MVC controller. 3 | Use CGLIB dynamic proxy service interface to RestController. 4 | 5 | ## Feature 6 | - Auto export feign without MVC controller 7 | - Can specify the package path for scanning. 8 | - Support Swagger 9 | 10 | ### Get Started 11 | 12 | ### Create Interface as Feign Client 13 | ~~~ 14 | /** 15 | * @author liqiu 16 | * @create 2018/9/21 13:52 17 | **/ 18 | @Api(tags = "DemoService", description = "Demo Feign Client") 19 | @FeignClient("demo-service") 20 | public interface DemoService { 21 | 22 | /** 23 | * create demo 24 | * 25 | * @param demo 26 | * @return 27 | */ 28 | @ApiOperation(value = "Create demo") 29 | @PostMapping(value = "/demo") 30 | Demo create(@RequestBody @Valid @ApiParam Demo demo); 31 | 32 | /** 33 | * update demo 34 | * 35 | * @param demo 36 | * @return 37 | */ 38 | @PutMapping(value = "/demo") 39 | Demo update(@RequestBody @Valid Demo demo); 40 | 41 | /** 42 | * delete demo 43 | * 44 | * @param id 45 | * @return 46 | */ 47 | @DeleteMapping(value = "/demo/{id}") 48 | Demo delete(@PathVariable(name = "id") String id); 49 | 50 | /** 51 | * list demo 52 | * 53 | * @param id 54 | * @param headerValue test header value 55 | * @return 56 | */ 57 | @GetMapping(value = "/demo/{id}") 58 | Demo get(@PathVariable(name = "id") String id, @RequestHeader(name = "header") String headerValue); 59 | 60 | /** 61 | * list demos 62 | * 63 | * @return 64 | */ 65 | @GetMapping(value = "/demos") 66 | List list(); 67 | 68 | /** 69 | * upload file 70 | * 71 | * @param file 72 | * @return 73 | */ 74 | @PostMapping(value = "/demo/upload") 75 | String upload(@RequestPart(name = "file") MultipartFile file); 76 | } 77 | 78 | ~~~ 79 | 80 | ### Create Implementor 81 | 82 | ~~~ 83 | @Slf4j 84 | @Primary 85 | @Service 86 | public class DemoServiceImpl implements DemoService { 87 | 88 | @Override 89 | public Demo create(Demo demo) { 90 | log.info("Create executed : " + demo); 91 | return demo; 92 | } 93 | 94 | @Override 95 | public Demo update(Demo demo) { 96 | log.info("Update execute :" + demo); 97 | return demo; 98 | } 99 | 100 | @Override 101 | public Demo delete(String id) { 102 | log.info("Delete execute : " + id); 103 | return Demo.builder().name("demo-" + id).data("data-" + id).build(); 104 | } 105 | 106 | @Override 107 | public Demo get(String id, String header) { 108 | Demo demo = Demo.builder() 109 | .name(header) 110 | .data(header).build(); 111 | System.out.println("Get execute : " + id + "," + header); 112 | return demo; 113 | } 114 | 115 | @Override 116 | public List list() { 117 | System.out.println("List execute"); 118 | List demos = new ArrayList<>(); 119 | for (int i = 0; i < 5; i++) { 120 | Demo demo = Demo.builder() 121 | .name("demo-" + i) 122 | .data("data" + i).build(); 123 | demos.add(demo); 124 | } 125 | return demos; 126 | } 127 | 128 | @Override 129 | public String upload(MultipartFile file) { 130 | return file.getOriginalFilename(); 131 | } 132 | } 133 | 134 | ~~~ 135 | 136 | ### Enable Feign Proxy for Application 137 | ~~~ 138 | @EnableFeignProxies(basePackages = "com.github.leecho") 139 | @ComponentScan("com.github.leecho") 140 | @SpringBootApplication 141 | public class DemoApplication { 142 | 143 | public static void main(String[] args) { 144 | SpringApplication.run(DemoApplication.class, args); 145 | } 146 | 147 | } 148 | ~~~ 149 | 150 | ### Run Test Case 151 | ~~~ 152 | mvn test 153 | ~~~ 154 | 155 | ### Console Output 156 | 157 | ~~~ 158 | 2018-11-13 18:42:12.027 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/{id}],methods=[GET]}" onto public final com.github.leecho.spring.feign.sample.model.Demo com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.get(java.lang.String,java.lang.String) 159 | 2018-11-13 18:42:12.027 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo],methods=[PUT]}" onto public final com.github.leecho.spring.feign.sample.model.Demo com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.update(com.github.leecho.spring.feign.sample.model.Demo) 160 | 2018-11-13 18:42:12.028 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/{id}],methods=[DELETE]}" onto public final com.github.leecho.spring.feign.sample.model.Demo com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.delete(java.lang.String) 161 | 2018-11-13 18:42:12.028 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo],methods=[POST]}" onto public final com.github.leecho.spring.feign.sample.model.Demo com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.create(com.github.leecho.spring.feign.sample.model.Demo) 162 | 2018-11-13 18:42:12.028 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demos],methods=[GET]}" onto public final java.util.List com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.list() 163 | 2018-11-13 18:42:12.029 INFO 2124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/upload],methods=[POST]}" onto public final java.lang.String com.github.leecho.spring.feign.sample.service.DemoService$$EnhancerByCGLIB$$bf7785b6.upload(org.springframework.web.multipart.MultipartFile) 164 | ~~~ 165 | 166 | ## Issues 167 | - @PathVariable @HeaderValue @CookieValue must use attr "name" for special 168 | - The real implementor of service interface must use @Primary to avoid bean conflicts -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.leecho 7 | spring-cloud-feign-proxy 8 | 0.0.1-SNAPSHOT 9 | 10 | spring-cloud-starter-feign-proxy 11 | spring-cloud-feign-proxy-sample 12 | 13 | pom 14 | 15 | spring-cloud-feign-proxy 16 | Auto Proxy Feign Interface 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-parent 21 | 2.0.5.RELEASE 22 | 23 | 24 | 25 | 26 | UTF-8 27 | UTF-8 28 | 1.8 29 | Finchley.SR1 30 | 31 | 32 | 33 | 34 | 35 | 36 | ${project.groupId} 37 | spring-cloud-starter-feign-proxy 38 | ${project.version} 39 | 40 | 41 | org.springframework.cloud 42 | spring-cloud-dependencies 43 | ${spring-cloud.version} 44 | pom 45 | import 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-feign-proxy 7 | com.github.leecho 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-cloud-feign-proxy-sample 13 | 14 | 15 | 16 | org.projectlombok 17 | lombok 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-test 22 | test 23 | 24 | 25 | com.github.leecho 26 | spring-cloud-starter-feign-proxy 27 | 28 | 29 | com.google.guava 30 | guava 31 | 25.0-jre 32 | 33 | 34 | io.springfox 35 | springfox-swagger2 36 | 2.9.2 37 | 38 | 39 | io.springfox 40 | springfox-swagger-ui 41 | 2.9.2 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | 53 | i 54 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/main/java/com/github/leecho/spring/feign/sample/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample; 2 | 3 | import com.github.leecho.spring.cloud.feign.EnableFeignProxies; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.ComponentScan; 7 | 8 | @EnableFeignProxies(basePackages = "com.github.leecho") 9 | @ComponentScan("com.github.leecho") 10 | @SpringBootApplication 11 | public class DemoApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(DemoApplication.class, args); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/main/java/com/github/leecho/spring/feign/sample/Swagger2AutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample; 2 | 3 | import com.google.common.base.Predicates; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.service.Contact; 11 | import springfox.documentation.spi.DocumentationType; 12 | import springfox.documentation.spring.web.plugins.Docket; 13 | import springfox.documentation.swagger.web.*; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * 通用Swagger配置 18 | * 19 | * @author LIQIU 20 | * @date 2018-3-14 21 | **/ 22 | @Configuration 23 | @EnableSwagger2 24 | public class Swagger2AutoConfiguration { 25 | 26 | 27 | @Bean 28 | public Docket createRestApi() { 29 | return new Docket(DocumentationType.SWAGGER_2) 30 | .useDefaultResponseMessages(false) 31 | .apiInfo(apiInfo()) 32 | .select() 33 | .apis(RequestHandlerSelectors.basePackage("com.github.leecho")) 34 | .build(); 35 | } 36 | 37 | private ApiInfo apiInfo() { 38 | return new ApiInfoBuilder() 39 | .title("Feign Proxy Demo") 40 | .description("Feign Clients of Demo") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/main/java/com/github/leecho/spring/feign/sample/model/Demo.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | /** 9 | * @author liqiu 10 | * @create 2018/9/21 13:58 11 | **/ 12 | @Data 13 | @Builder 14 | @AllArgsConstructor 15 | @NoArgsConstructor 16 | public class Demo { 17 | 18 | private String name; 19 | 20 | private String data; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/main/java/com/github/leecho/spring/feign/sample/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample.service; 2 | 3 | import com.github.leecho.spring.feign.sample.model.Demo; 4 | import io.swagger.annotations.Api; 5 | import io.swagger.annotations.ApiOperation; 6 | import io.swagger.annotations.ApiParam; 7 | import org.springframework.cloud.openfeign.FeignClient; 8 | import org.springframework.web.bind.annotation.*; 9 | import org.springframework.web.multipart.MultipartFile; 10 | 11 | import javax.validation.Valid; 12 | import java.util.List; 13 | 14 | /** 15 | * @author liqiu 16 | * @create 2018/9/21 13:52 17 | **/ 18 | @Api(tags = "DemoService", description = "Demo Feign Client") 19 | @FeignClient("demo-service") 20 | public interface DemoService { 21 | 22 | /** 23 | * create demo 24 | * 25 | * @param demo 26 | * @return 27 | */ 28 | @ApiOperation(value = "Create demo") 29 | @PostMapping(value = "/demo") 30 | Demo create(@RequestBody @Valid @ApiParam Demo demo); 31 | 32 | /** 33 | * update demo 34 | * 35 | * @param demo 36 | * @return 37 | */ 38 | @PutMapping(value = "/demo") 39 | Demo update(@RequestBody @Valid Demo demo); 40 | 41 | /** 42 | * delete demo 43 | * 44 | * @param id 45 | * @return 46 | */ 47 | @DeleteMapping(value = "/demo/{id}") 48 | Demo delete(@PathVariable(name = "id") String id); 49 | 50 | /** 51 | * list demo 52 | * 53 | * @param id 54 | * @param headerValue test header value 55 | * @return 56 | */ 57 | @GetMapping(value = "/demo/{id}") 58 | Demo get(@PathVariable(name = "id") String id, @RequestHeader(name = "header") String headerValue); 59 | 60 | /** 61 | * list demos 62 | * 63 | * @return 64 | */ 65 | @GetMapping(value = "/demos") 66 | List list(); 67 | 68 | /** 69 | * upload file 70 | * 71 | * @param file 72 | * @return 73 | */ 74 | @PostMapping(value = "/demo/upload") 75 | String upload(@RequestPart(name = "file") MultipartFile file); 76 | } 77 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/main/java/com/github/leecho/spring/feign/sample/service/impl/DemoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample.service.impl; 2 | 3 | import com.github.leecho.spring.feign.sample.model.Demo; 4 | import com.github.leecho.spring.feign.sample.service.DemoService; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.context.annotation.Primary; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * @author liqiu 15 | * @create 2018/9/21 14:00 16 | **/ 17 | @Slf4j 18 | @Primary 19 | @Service 20 | public class DemoServiceImpl implements DemoService { 21 | 22 | @Override 23 | public Demo create(Demo demo) { 24 | log.info("Create executed : " + demo); 25 | return demo; 26 | } 27 | 28 | @Override 29 | public Demo update(Demo demo) { 30 | log.info("Update execute :" + demo); 31 | return demo; 32 | } 33 | 34 | @Override 35 | public Demo delete(String id) { 36 | log.info("Delete execute : " + id); 37 | return Demo.builder().name("demo-" + id).data("data-" + id).build(); 38 | } 39 | 40 | @Override 41 | public Demo get(String id, String header) { 42 | Demo demo = Demo.builder() 43 | .name(header) 44 | .data(header).build(); 45 | System.out.println("Get execute : " + id + "," + header); 46 | return demo; 47 | } 48 | 49 | @Override 50 | public List list() { 51 | System.out.println("List execute"); 52 | List demos = new ArrayList<>(); 53 | for (int i = 0; i < 5; i++) { 54 | Demo demo = Demo.builder() 55 | .name("demo-" + i) 56 | .data("data" + i).build(); 57 | demos.add(demo); 58 | } 59 | return demos; 60 | } 61 | 62 | @Override 63 | public String upload(MultipartFile file) { 64 | return file.getOriginalFilename(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /spring-cloud-feign-proxy-sample/src/test/java/com/github/leecho/spring/feign/sample/service/impl/DemoApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.feign.sample.service.impl; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.github.leecho.spring.feign.sample.model.Demo; 5 | import org.hamcrest.Matchers; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.mock.web.MockMultipartFile; 13 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 14 | import org.springframework.test.context.web.WebAppConfiguration; 15 | import org.springframework.test.web.servlet.MockMvc; 16 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 17 | import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 18 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 19 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 20 | import org.springframework.web.context.WebApplicationContext; 21 | 22 | import javax.servlet.http.Cookie; 23 | 24 | import static org.junit.Assert.*; 25 | 26 | /** 27 | * @author LIQIU 28 | * created on 2018-11-6 29 | **/ 30 | @SpringBootTest 31 | @RunWith(SpringJUnit4ClassRunner.class) 32 | @WebAppConfiguration 33 | public class DemoApplicationTest { 34 | @Autowired 35 | private WebApplicationContext context; 36 | 37 | private MockMvc mvc; 38 | 39 | @Before 40 | public void setUp() { 41 | mvc = MockMvcBuilders.webAppContextSetup(context).build(); 42 | } 43 | 44 | @Test 45 | public void create() throws Exception { 46 | mvc.perform(MockMvcRequestBuilders.post("/demo") 47 | .contentType(MediaType.APPLICATION_JSON_UTF8) 48 | .content(new ObjectMapper().writeValueAsString(Demo.builder().name("create").data("data").build())) 49 | .accept(MediaType.APPLICATION_JSON)) 50 | .andExpect(MockMvcResultMatchers.status().isOk()) 51 | .andDo(MockMvcResultHandlers.print()); 52 | 53 | } 54 | 55 | @Test 56 | public void update() throws Exception { 57 | mvc.perform(MockMvcRequestBuilders.put("/demo") 58 | .contentType(MediaType.APPLICATION_JSON_UTF8) 59 | .content(new ObjectMapper().writeValueAsString(Demo.builder().name("update").data("data").build())) 60 | .accept(MediaType.APPLICATION_JSON)) 61 | .andExpect(MockMvcResultMatchers.status().isOk()) 62 | .andDo(MockMvcResultHandlers.print()); 63 | 64 | } 65 | 66 | @Test 67 | public void delete() throws Exception { 68 | mvc.perform(MockMvcRequestBuilders.delete("/demo/{id}", "1") 69 | .contentType(MediaType.APPLICATION_JSON_UTF8) 70 | .accept(MediaType.APPLICATION_JSON)) 71 | .andExpect(MockMvcResultMatchers.status().isOk()) 72 | .andDo(MockMvcResultHandlers.print()); 73 | 74 | } 75 | 76 | @Test 77 | public void get() throws Exception { 78 | mvc.perform(MockMvcRequestBuilders.get("/demo/{id}", "1") 79 | .contentType(MediaType.APPLICATION_JSON_UTF8) 80 | .header("header", "header-value") 81 | .accept(MediaType.APPLICATION_JSON)) 82 | .andExpect(MockMvcResultMatchers.status().isOk()) 83 | .andDo(MockMvcResultHandlers.print()); 84 | 85 | } 86 | 87 | @Test 88 | public void list() throws Exception { 89 | mvc.perform(MockMvcRequestBuilders.get("/demos") 90 | .contentType(MediaType.APPLICATION_JSON_UTF8) 91 | .accept(MediaType.APPLICATION_JSON)) 92 | .andExpect(MockMvcResultMatchers.status().isOk()) 93 | .andDo(MockMvcResultHandlers.print()); 94 | 95 | } 96 | 97 | @Test 98 | public void upload() throws Exception { 99 | mvc.perform(MockMvcRequestBuilders.multipart("/demo/upload").file(new MockMultipartFile("file", "test.txt", ",multipart/form-data", "upload test".getBytes())) 100 | .accept(MediaType.APPLICATION_JSON)) 101 | .andExpect(MockMvcResultMatchers.status().isOk()) 102 | .andDo(MockMvcResultHandlers.print()); 103 | 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-feign-proxy 7 | com.github.leecho 8 | 0.0.1-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | spring-cloud-starter-feign-proxy 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-web 17 | 18 | 19 | org.springframework.cloud 20 | spring-cloud-starter-openfeign 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/src/main/java/com/github/leecho/spring/cloud/feign/EnableFeignProxies.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.cloud.feign; 2 | 3 | import org.springframework.cloud.openfeign.FeignClient; 4 | import org.springframework.context.annotation.Import; 5 | 6 | import java.lang.annotation.*; 7 | 8 | /** 9 | * Scans for interfaces that declare they are feign clients (via {@link FeignClient 10 | * @FeignClient}). Configures component scanning directives for use with 11 | * {@link org.springframework.context.annotation.Configuration 12 | * @Configuration} classes. 13 | * 14 | * @author Spencer Gibb 15 | * @author Dave Syer 16 | * @since 1.0 17 | */ 18 | @Retention(RetentionPolicy.RUNTIME) 19 | @Target(ElementType.TYPE) 20 | @Documented 21 | @Import({FeignProxiesRegistrar.class, FeignProxyMvcConfiguration.class}) 22 | public @interface EnableFeignProxies { 23 | 24 | /** 25 | * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation 26 | * declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of 27 | * {@code @ComponentScan(basePackages="org.my.pkg")}. 28 | * 29 | * @return the array of 'basePackages'. 30 | */ 31 | String[] value() default {}; 32 | 33 | /** 34 | * Base packages to scan for annotated components. 35 | *

36 | * {@link #value()} is an alias for (and mutually exclusive with) this attribute. 37 | *

38 | * Use {@link #basePackageClasses()} for a type-safe alternative to String-based 39 | * package names. 40 | * 41 | * @return the array of 'basePackages'. 42 | */ 43 | String[] basePackages() default {}; 44 | 45 | /** 46 | * Type-safe alternative to {@link #basePackages()} for specifying the packages to 47 | * scan for annotated components. The package of each class specified will be scanned. 48 | *

49 | * Consider creating a special no-op marker class or interface in each package that 50 | * serves no purpose other than being referenced by this attribute. 51 | * 52 | * @return the array of 'basePackageClasses'. 53 | */ 54 | Class[] basePackageClasses() default {}; 55 | 56 | /** 57 | * List of classes annotated with @FeignClient. If not empty, disables classpath scanning. 58 | * 59 | * @return 60 | */ 61 | Class[] clients() default {}; 62 | 63 | Class superClass() default Void.class; 64 | } 65 | -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/src/main/java/com/github/leecho/spring/cloud/feign/FeignProxiesRegistrar.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.cloud.feign; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.BeansException; 6 | import org.springframework.beans.factory.BeanFactory; 7 | import org.springframework.beans.factory.BeanFactoryAware; 8 | import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; 9 | import org.springframework.beans.factory.config.BeanDefinition; 10 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 11 | import org.springframework.beans.factory.support.DefaultListableBeanFactory; 12 | import org.springframework.cglib.proxy.Enhancer; 13 | import org.springframework.cloud.openfeign.FeignClient; 14 | import org.springframework.context.EnvironmentAware; 15 | import org.springframework.context.ResourceLoaderAware; 16 | import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; 17 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; 18 | import org.springframework.core.env.Environment; 19 | import org.springframework.core.io.ResourceLoader; 20 | import org.springframework.core.type.AnnotationMetadata; 21 | import org.springframework.core.type.ClassMetadata; 22 | import org.springframework.core.type.classreading.MetadataReader; 23 | import org.springframework.core.type.classreading.MetadataReaderFactory; 24 | import org.springframework.core.type.filter.AbstractClassTestingTypeFilter; 25 | import org.springframework.core.type.filter.AnnotationTypeFilter; 26 | import org.springframework.core.type.filter.TypeFilter; 27 | import org.springframework.util.Assert; 28 | import org.springframework.util.ClassUtils; 29 | import org.springframework.util.StringUtils; 30 | 31 | import java.io.IOException; 32 | import java.util.*; 33 | 34 | /** 35 | * @author Spencer Gibb 36 | * @author Jakub Narloch 37 | * @author Venil Noronha 38 | * @author Gang Li 39 | */ 40 | class FeignProxiesRegistrar implements ImportBeanDefinitionRegistrar, 41 | ResourceLoaderAware, EnvironmentAware, BeanFactoryAware { 42 | 43 | private Logger logger = LoggerFactory.getLogger(FeignProxiesRegistrar.class); 44 | 45 | // patterned after Spring Integration IntegrationComponentScanRegistrar 46 | // and RibbonClientsConfigurationRegistgrar 47 | 48 | private ResourceLoader resourceLoader; 49 | 50 | private Environment environment; 51 | 52 | private BeanFactory beanFactory; 53 | 54 | public FeignProxiesRegistrar() { 55 | } 56 | 57 | @Override 58 | public void setResourceLoader(ResourceLoader resourceLoader) { 59 | this.resourceLoader = resourceLoader; 60 | } 61 | 62 | @Override 63 | public void registerBeanDefinitions(AnnotationMetadata metadata, 64 | BeanDefinitionRegistry registry) { 65 | registerFeignClients(metadata, registry); 66 | } 67 | 68 | public void registerFeignClients(AnnotationMetadata metadata, 69 | BeanDefinitionRegistry registry) { 70 | ClassPathScanningCandidateComponentProvider scanner = getScanner(); 71 | scanner.setResourceLoader(this.resourceLoader); 72 | 73 | Set basePackages; 74 | Map attrs = metadata.getAnnotationAttributes(EnableFeignProxies.class.getName()); 75 | 76 | AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(FeignClient.class); 77 | final Class[] clients = attrs == null ? null : (Class[]) attrs.get("clients"); 78 | 79 | Class superClass = attrs == null ? null : (Class) attrs.get("superClass"); 80 | superClass = superClass.equals(Void.class) ? null : superClass; 81 | 82 | if (clients == null || clients.length == 0) { 83 | scanner.addIncludeFilter(annotationTypeFilter); 84 | basePackages = getBasePackages(metadata); 85 | } else { 86 | final Set clientClasses = new HashSet<>(); 87 | basePackages = new HashSet<>(); 88 | for (Class clazz : clients) { 89 | basePackages.add(ClassUtils.getPackageName(clazz)); 90 | clientClasses.add(clazz.getCanonicalName()); 91 | } 92 | AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() { 93 | @Override 94 | protected boolean match(ClassMetadata metadata) { 95 | String cleaned = metadata.getClassName().replaceAll("\\$", "."); 96 | return clientClasses.contains(cleaned); 97 | } 98 | }; 99 | scanner.addIncludeFilter(new FeignProxiesRegistrar.AllTypeFilter(Arrays.asList(filter, annotationTypeFilter))); 100 | } 101 | 102 | DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory; 103 | 104 | for (String basePackage : basePackages) { 105 | Set candidateComponents = scanner.findCandidateComponents(basePackage); 106 | for (BeanDefinition candidateComponent : candidateComponents) { 107 | if (candidateComponent instanceof AnnotatedBeanDefinition) { 108 | // verify annotated class is an interface 109 | AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent; 110 | AnnotationMetadata annotationMetadata = beanDefinition.getMetadata(); 111 | Assert.isTrue(annotationMetadata.isInterface(), "@FeignClient can only be specified on an interface"); 112 | 113 | Class interfaceClass = null; 114 | try { 115 | interfaceClass = Class.forName(beanDefinition.getBeanClassName()); 116 | } catch (ClassNotFoundException e) { 117 | e.printStackTrace(); 118 | } 119 | 120 | //Proxy Feign Client 121 | if (interfaceClass != null) { 122 | Object bean = beanFactory.getBean(interfaceClass); 123 | if (bean != null) { 124 | Enhancer enhancer = new Enhancer(); 125 | if (superClass != null) { 126 | enhancer.setSuperclass(superClass); 127 | } 128 | enhancer.setCallback(new FeignProxyInvocationHandler(bean)); 129 | enhancer.setInterfaces(new Class[]{interfaceClass, FeignProxyController.class}); 130 | Object proxy = enhancer.create(); 131 | defaultListableBeanFactory.registerSingleton(StringUtils.capitalize(interfaceClass.getSimpleName()) + "$FeignProxyController", proxy); 132 | if (logger.isDebugEnabled()) { 133 | logger.debug("Feign client {} proxy by {}", interfaceClass, proxy); 134 | } 135 | } else { 136 | if (logger.isDebugEnabled()) { 137 | logger.debug("Feign client {} no implementor founded", interfaceClass); 138 | } 139 | } 140 | } 141 | } 142 | } 143 | } 144 | } 145 | 146 | private String resolve(String value) { 147 | if (StringUtils.hasText(value)) { 148 | return this.environment.resolvePlaceholders(value); 149 | } 150 | return value; 151 | } 152 | 153 | 154 | protected ClassPathScanningCandidateComponentProvider getScanner() { 155 | return new ClassPathScanningCandidateComponentProvider(false, this.environment) { 156 | @Override 157 | protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { 158 | boolean isCandidate = false; 159 | if (beanDefinition.getMetadata().isIndependent()) { 160 | if (!beanDefinition.getMetadata().isAnnotation()) { 161 | isCandidate = true; 162 | } 163 | } 164 | return isCandidate; 165 | } 166 | }; 167 | } 168 | 169 | protected Set getBasePackages(AnnotationMetadata importingClassMetadata) { 170 | Map attributes = importingClassMetadata 171 | .getAnnotationAttributes(EnableFeignProxies.class.getCanonicalName()); 172 | 173 | Set basePackages = new HashSet<>(); 174 | for (String pkg : (String[]) attributes.get("value")) { 175 | if (StringUtils.hasText(pkg)) { 176 | basePackages.add(pkg); 177 | } 178 | } 179 | for (String pkg : (String[]) attributes.get("basePackages")) { 180 | if (StringUtils.hasText(pkg)) { 181 | basePackages.add(pkg); 182 | } 183 | } 184 | for (Class clazz : (Class[]) attributes.get("basePackageClasses")) { 185 | basePackages.add(ClassUtils.getPackageName(clazz)); 186 | } 187 | 188 | if (basePackages.isEmpty()) { 189 | basePackages.add( 190 | ClassUtils.getPackageName(importingClassMetadata.getClassName())); 191 | } 192 | return basePackages; 193 | } 194 | 195 | private String getQualifier(Map client) { 196 | if (client == null) { 197 | return null; 198 | } 199 | String qualifier = (String) client.get("qualifier"); 200 | if (StringUtils.hasText(qualifier)) { 201 | return qualifier; 202 | } 203 | return null; 204 | } 205 | 206 | private String getClientName(Map client) { 207 | if (client == null) { 208 | return null; 209 | } 210 | String value = (String) client.get("value"); 211 | if (!StringUtils.hasText(value)) { 212 | value = (String) client.get("name"); 213 | } 214 | if (!StringUtils.hasText(value)) { 215 | value = (String) client.get("serviceId"); 216 | } 217 | if (StringUtils.hasText(value)) { 218 | return value; 219 | } 220 | 221 | throw new IllegalStateException("Either 'name' or 'value' must be provided in @" 222 | + FeignClient.class.getSimpleName()); 223 | } 224 | 225 | 226 | @Override 227 | public void setEnvironment(Environment environment) { 228 | this.environment = environment; 229 | } 230 | 231 | 232 | @Override 233 | public void setBeanFactory(BeanFactory beanFactory) throws BeansException { 234 | this.beanFactory = beanFactory; 235 | } 236 | 237 | /** 238 | * Helper class to create a {@link TypeFilter} that matches if all the delegates 239 | * match. 240 | * 241 | * @author Oliver Gierke 242 | */ 243 | private static class AllTypeFilter implements TypeFilter { 244 | 245 | private final List delegates; 246 | 247 | /** 248 | * Creates a new {@link AllTypeFilter} to match if all the given delegates match. 249 | * 250 | * @param delegates must not be {@literal null}. 251 | */ 252 | public AllTypeFilter(List delegates) { 253 | Assert.notNull(delegates, "This argument is required, it must not be null"); 254 | this.delegates = delegates; 255 | } 256 | 257 | @Override 258 | public boolean match(MetadataReader metadataReader, 259 | MetadataReaderFactory metadataReaderFactory) throws IOException { 260 | 261 | for (TypeFilter filter : this.delegates) { 262 | if (!filter.match(metadataReader, metadataReaderFactory)) { 263 | return false; 264 | } 265 | } 266 | 267 | return true; 268 | } 269 | } 270 | } -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/src/main/java/com/github/leecho/spring/cloud/feign/FeignProxyController.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.cloud.feign; 2 | 3 | import org.springframework.web.bind.annotation.RestController; 4 | 5 | /** 6 | * Defining special class as a feign proxy controller 7 | * 8 | * @author liqiu 9 | * created on 2018/10/18 17:13 10 | **/ 11 | @RestController 12 | public interface FeignProxyController { 13 | } 14 | -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/src/main/java/com/github/leecho/spring/cloud/feign/FeignProxyInvocationHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.cloud.feign; 2 | 3 | import org.springframework.aop.support.AopUtils; 4 | import org.springframework.cglib.proxy.InvocationHandler; 5 | 6 | import java.lang.reflect.Method; 7 | 8 | /** 9 | * @author liqiu 10 | * created on 2018/10/18 17:52 11 | **/ 12 | public class FeignProxyInvocationHandler implements InvocationHandler { 13 | 14 | private Object target; 15 | 16 | public FeignProxyInvocationHandler(Object target) { 17 | this.target = target; 18 | } 19 | 20 | @Override 21 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 22 | if (method.getName().equals("toString")) { 23 | return AopUtils.getTargetClass(proxy).toString(); 24 | } 25 | if (method.getName().equals("equals")) { 26 | return method.invoke(AopUtils.getTargetClass(proxy), args); 27 | } 28 | if (method.getName().equals("hashCode")) { 29 | return AopUtils.getTargetClass(proxy).hashCode(); 30 | } 31 | return method.invoke(target,args); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /spring-cloud-starter-feign-proxy/src/main/java/com/github/leecho/spring/cloud/feign/FeignProxyMvcConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.github.leecho.spring.cloud.feign; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.config.ConfigurableBeanFactory; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.core.DefaultParameterNameDiscoverer; 7 | import org.springframework.core.GenericTypeResolver; 8 | import org.springframework.core.MethodParameter; 9 | import org.springframework.core.ResolvableType; 10 | import org.springframework.core.convert.ConversionService; 11 | import org.springframework.web.bind.WebDataBinder; 12 | import org.springframework.web.bind.annotation.*; 13 | import org.springframework.web.bind.support.WebDataBinderFactory; 14 | import org.springframework.web.context.request.NativeWebRequest; 15 | import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver; 16 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 17 | import org.springframework.web.method.support.ModelAndViewContainer; 18 | import org.springframework.web.servlet.mvc.method.annotation.*; 19 | import org.springframework.web.util.UriComponentsBuilder; 20 | 21 | import javax.annotation.PostConstruct; 22 | import javax.validation.Valid; 23 | import java.lang.annotation.Annotation; 24 | import java.lang.reflect.Method; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | import java.util.Map; 28 | 29 | /** 30 | * @author liqiu 31 | * created on 2018/10/24 17:03 32 | **/ 33 | public class FeignProxyMvcConfiguration { 34 | 35 | @Autowired 36 | private RequestMappingHandlerAdapter adapter; 37 | 38 | @Autowired 39 | private ConfigurableBeanFactory beanFactory; 40 | 41 | public static MethodParameter interfaceMethodParameter(MethodParameter parameter, Class annotationType) { 42 | if (!parameter.hasParameterAnnotation(annotationType)) { 43 | for (Class itf : parameter.getDeclaringClass().getInterfaces()) { 44 | try { 45 | Method method = itf.getMethod(parameter.getMethod().getName(), parameter.getMethod().getParameterTypes()); 46 | MethodParameter itfParameter = new MethodParameter(method, parameter.getParameterIndex()); 47 | if (itfParameter.hasParameterAnnotation(annotationType)) { 48 | parameter.initParameterNameDiscovery(new DefaultParameterNameDiscoverer()); 49 | GenericTypeResolver.resolveParameterType(itfParameter,itf); 50 | return itfParameter; 51 | } 52 | } catch (NoSuchMethodException e) { 53 | continue; 54 | } 55 | } 56 | } 57 | return parameter; 58 | } 59 | 60 | @PostConstruct 61 | public void modifyArgumentResolvers() { 62 | List list = new ArrayList<>(adapter.getArgumentResolvers()); 63 | 64 | // PathVariable 支持接口注解 65 | list.add(0, new PathVariableMethodArgumentResolver() { 66 | @Override 67 | public boolean supportsParameter(MethodParameter parameter) { 68 | return super.supportsParameter(interfaceMethodParameter(parameter, PathVariable.class)); 69 | } 70 | 71 | @Override 72 | protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { 73 | return super.createNamedValueInfo(interfaceMethodParameter(parameter, PathVariable.class)); 74 | } 75 | 76 | @Override 77 | public void contributeMethodArgument(MethodParameter parameter, Object value, 78 | UriComponentsBuilder builder, Map uriVariables, ConversionService conversionService) { 79 | super.contributeMethodArgument(interfaceMethodParameter(parameter, PathVariable.class), value, builder, uriVariables, conversionService); 80 | } 81 | }); 82 | 83 | // RequestHeader 支持接口注解 84 | list.add(0, new RequestHeaderMethodArgumentResolver(beanFactory) { 85 | @Override 86 | public boolean supportsParameter(MethodParameter parameter) { 87 | return super.supportsParameter(interfaceMethodParameter(parameter, RequestHeader.class)); 88 | } 89 | 90 | @Override 91 | protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { 92 | return super.createNamedValueInfo(interfaceMethodParameter(parameter, RequestHeader.class)); 93 | } 94 | }); 95 | 96 | // CookieValue 支持接口注解 97 | list.add(0, new ServletCookieValueMethodArgumentResolver(beanFactory) { 98 | @Override 99 | public boolean supportsParameter(MethodParameter parameter) { 100 | return super.supportsParameter(interfaceMethodParameter(parameter, CookieValue.class)); 101 | } 102 | 103 | @Override 104 | protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { 105 | return super.createNamedValueInfo(interfaceMethodParameter(parameter, CookieValue.class)); 106 | } 107 | }); 108 | 109 | // RequestBody Valid 支持接口注解 110 | list.add(0, new RequestResponseBodyMethodProcessor(adapter.getMessageConverters()) { 111 | @Override 112 | public boolean supportsParameter(MethodParameter parameter) { 113 | return super.supportsParameter(interfaceMethodParameter(parameter, RequestBody.class)); 114 | } 115 | 116 | @Override 117 | protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) { 118 | super.validateIfApplicable(binder, interfaceMethodParameter(methodParam, Valid.class)); 119 | } 120 | }); 121 | 122 | list.add(0,new RequestPartMethodArgumentResolver(adapter.getMessageConverters()){ 123 | @Override 124 | public boolean supportsParameter(MethodParameter parameter) { 125 | return super.supportsParameter(interfaceMethodParameter(parameter, RequestPart.class)); 126 | } 127 | 128 | @Override 129 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { 130 | return super.resolveArgument(interfaceMethodParameter(parameter, RequestPart.class), mavContainer, request, binderFactory); 131 | } 132 | }); 133 | 134 | adapter.setArgumentResolvers(list); 135 | } 136 | } 137 | --------------------------------------------------------------------------------