提交 5830c575 编写于 作者: 如梦技术's avatar 如梦技术 🐛

测试通过

上级
# http://editorconfig.org
root = true
# 空格替代Tab缩进在各种编辑工具下效果一致
[*]
indent_style = space
indent_size = 4
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
[*.java]
indent_style = tab
indent_size = 4
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
### gradle ###
.gradle
!gradle/wrapper/gradle-wrapper.jar
### STS ###
.settings/
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
bin/
### IntelliJ IDEA ###
.idea
out/
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### maven ###
target/
*.war
*.ear
*.zip
*.tar
*.tar.gz
# logs #
logs
# temp ignore
*.log
*.cache
*.diff
*.patch
*.tmp
*.java~
*.properties~
*.xml~
# system ignore
.DS_Store
Thumbs.db
Servers
.metadata
upload
gen_code
The MIT License (MIT)
Copyright (c) 2018 如梦技术
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
## 说明
jfinal weixin 的 spring boot starter,这个starter是为了方便boot用户使用。
具体demo请查看:`spring-boot-weixin-demo`
## Jar包依赖
```xml
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>spring-boot-starter-weixin</artifactId>
<version>1.0.0</version>
</dependency>
```
`说明`:依赖`spring-boot-starter-aop`
## 使用
### 启用微信
```java
@EnableDreamWeixin
```
### 消息
#### 公众号
1. 继承`MsgControllerAdapter`,实现需要重写的消息。
2. 添加注解`@WxMsgController`,注解value为你的消息地址,使用/weixin/wx
### 小程序
1. 继承`WxaMsgController`,实现需要重写的消息。
2. 添加注解`@WxMsgController`,注解value为你的消息地址,使用/weixin/wxa
### Api
1. 使用传统的spring的控制器即可
2. 添加`@WxApi`注解
### 配置
| 配置项 | 默认值 |
| ----- | ------ |
| dream.weixin.access-token-cache | dreamWeixinCache |
| dream.weixin.app-id-key | appId |
| dream.weixin.dev-mode | false |
| dream.weixin.url-patterns | /weixin/* |
| dream.weixin.wx-configs | 公众号的配置 |
| dream.weixin.wxa-config | 小程序配置 |
`注意`
- cache使用spring的cache,需要`@EnableCaching`开启。
- `access-token-cache`建议配置有效时间7100秒。
## 捐助共勉
<img src="https://gitee.com/uploads/images/2018/0311/153544_5afb12b1_372.jpeg" width="250px"/>
<img src="https://gitee.com/uploads/images/2018/0311/153556_679db579_372.jpeg" width="250px"/>
## VIP群
捐助¥199即可加入如梦技术VIP,捐助后联系QQ: 596392912
#### VIP权益
1. spring boot版安全框架(maven + spring boot + spring security + thymeleaf)
2. 技术资料共享
3. spring cloud脚手架(改造中)
4. 更多私有Git资源,
buildscript {
repositories {
maven { url 'http://repo.spring.io/plugins-release' }
}
dependencies {
classpath("io.spring.gradle:propdeps-plugin:0.0.10.RELEASE")
classpath("io.spring.gradle:dependency-management-plugin:1.0.4.RELEASE")
}
}
apply plugin: 'maven'
apply plugin: 'signing'
apply plugin: 'propdeps'
apply plugin: 'propdeps-maven'
apply plugin: 'io.spring.dependency-management'
ext {
javaVersion = JavaVersion.VERSION_1_8
springVersion = "4.3.14.RELEASE"
springBootVersion = "1.5.10.RELEASE"
jfinalVersion = "3.3"
jfinalWeixinVersion = "1.9"
junitVersion = "4.12"
lombokVersion = '1.16.20'
}
repositories {
mavenLocal()
maven { url "https://repo.spring.io/libs-release" }
maven { url "https://repo.spring.io/milestone" }
maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
mavenCentral()
}
dependencies {
compile "com.jfinal:jfinal:${jfinalVersion}"
compile "com.jfinal:jfinal-weixin:${jfinalWeixinVersion}"
provided "org.springframework.boot:spring-boot-starter-web"
provided "org.springframework.boot:spring-boot-starter-aop"
optional "org.springframework.boot:spring-boot-configuration-processor"
provided "org.projectlombok:lombok:${lombokVersion}"
testCompile "junit:junit:${junitVersion}"
}
dependencyManagement {
imports {
mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}"
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
javadoc {
options {
encoding "UTF-8"
charSet 'UTF-8'
author true
version true
failOnError false
links "http://docs.oracle.com/javase/8/docs/api"
}
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from 'build/docs/javadoc'
}
artifacts {
archives sourcesJar
archives javadocJar
}
group = GROUPID
version = VERSION
uploadArchives {
repositories {
mavenDeployer {
pom.version = "$project.version"
pom.artifactId = "$project.name"
pom.groupId = "$project.group"
signing {
Sign archives
}
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: pom.version.endsWith('SNAPSHOT')
? 'https://oss.sonatype.org/content/repositories/snapshots/'
: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
) {
authentication(userName: userName, password: passWord)
}
pom.project {
name 'LuTool'
packaging 'jar'
description 'An enhanced toolkit of Spring boot to simplify development.'
url 'https://gitee.com/dreamlu/LuTool'
scm {
connection 'scm:git@gitee.com:/596392912/spring-boot-starter-weixin.git'
developerConnection 'scm:git@gitee.com/596392912/spring-boot-starter-weixin.git'
url 'https://gitee.com/596392912/spring-boot-starter-weixin'
}
licenses {
license {
name 'The MIT License (MIT)'
url 'http://opensource.org/licenses/MIT'
}
}
developers {
developer {
name 'Dreamlu'
email 'qq596392912@gmail.com'
}
}
}
}
}
}
VERSION=1.0.0
GROUPID=net.dreamlu
userName=chunmeng
passWord=sonatype
signing.keyId=D73A4CFE
signing.password=sonatype
signing.secretKeyRingFile=/Users/lcm/.gnupg/secring.gpg
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4.1-bin.zip
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
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
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
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
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'spring-boot-starter-weixin'
package net.dreamlu.weixin.annotation;
public enum ApiType {
/**
* 微信
*/
WX,
/**
* 小程序
*/
WXA
}
package net.dreamlu.weixin.annotation;
import net.dreamlu.weixin.config.DreamWeixinAutoConfiguration;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({
DreamWeixinProperties.class,
DreamWeixinAutoConfiguration.class
})
public @interface EnableDreamWeixin {}
package net.dreamlu.weixin.annotation;
import java.lang.annotation.*;
/**
* 微信Api接口注解用于拦截器
*
* @author L.cm
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WxApi {
// /**
// * 目前不支持多小程序
// * @return {ApiType}
// */
// ApiType value() default ApiType.WX;
}
package net.dreamlu.weixin.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
/**
* 微信消息控制器
*
* @author L.cm
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface WxMsgController {
String value() default "/";
}
package net.dreamlu.weixin.aspect;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.weixin.annotation.WxApi;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Order
@Slf4j
public class WxApiAspect {
private final DreamWeixinProperties weixinProperties;
public WxApiAspect(DreamWeixinProperties weixinProperties) {
this.weixinProperties = weixinProperties;
}
@Around("@annotation(wxApi)")
public Object aroundWxApi(ProceedingJoinPoint point, WxApi wxApi) throws Throwable {
// 目前不支持多小程序,所以不用判断是否为小程序
HttpServletRequest request = getRequest();
try {
String appId = request.getParameter(weixinProperties.getAppIdKey());
ApiConfigKit.setThreadLocalAppId(appId);
return point.proceed();
} finally {
ApiConfigKit.removeThreadLocalAppId();
}
}
/**
* 获取 HttpServletRequest
* @return {HttpServletRequest}
*/
private HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
package net.dreamlu.weixin.cache;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import org.springframework.cache.Cache;
public class SpringAccessTokenCache implements IAccessTokenCache {
private final String ACCESS_TOKEN_PREFIX = "dream-weixin:token:";
private final Cache cache;
public SpringAccessTokenCache(Cache cache) {
this.cache = cache;
}
@Override
public String get(String key) {
return cache.get(ACCESS_TOKEN_PREFIX + key, String.class);
}
@Override
public void set(String key, String jsonValue) {
cache.put(key, jsonValue);
}
@Override
public void remove(String key) {
cache.evict(key);
}
}
package net.dreamlu.weixin.config;
import com.jfinal.core.JFinalFilter;
import net.dreamlu.weixin.aspect.WxApiAspect;
import net.dreamlu.weixin.cache.SpringAccessTokenCache;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
@Configuration
@AutoConfigureAfter(DreamWeixinProperties.class)
public class DreamWeixinAutoConfiguration {
private final CacheManager cacheManager;
private final DreamWeixinProperties weixinProperties;
public DreamWeixinAutoConfiguration(CacheManager cacheManager, DreamWeixinProperties weixinProperties) {
this.cacheManager = cacheManager;
this.weixinProperties = weixinProperties;
}
@Bean
public FilterRegistrationBean jfinalFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
JFinalFilter jfinalFilter = new JFinalFilter();
registration.setFilter(jfinalFilter);
registration.addUrlPatterns(weixinProperties.getUrlPatterns());
// 添加JFinal configClass参数
registration.addInitParameter("configClass", DreamWeixinConfig.class.getName());
registration.setName("jfinalFilter");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
@Bean
public WeixinAppConfig weixinAppConfig() {
return new WeixinAppConfig(weixinProperties);
}
@Bean
public SpringAccessTokenCache springAccessTokenCache() {
Cache cache = cacheManager.getCache(weixinProperties.getAccessTokenCache());
return new SpringAccessTokenCache(cache);
}
@Bean
public WxApiAspect wxApiAspect() {
return new WxApiAspect(weixinProperties);
}
}
package net.dreamlu.weixin.config;
import com.jfinal.config.*;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.json.JacksonFactory;
import com.jfinal.template.Engine;
import net.dreamlu.weixin.annotation.WxMsgController;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import java.util.Map;
public class DreamWeixinConfig extends JFinalConfig {
@Override
public void configConstant(Constants me) {
me.setJsonFactory(new JacksonFactory());
me.setControllerFactory(new SpringControllerFactory());
}
@Override
public void configRoute(Routes me) {
findAnnotatedBeans(me);
}
@Override
public void configEngine(Engine me) {}
@Override
public void configPlugin(Plugins me) {}
@Override
public void configInterceptor(Interceptors me) {}
@Override
public void configHandler(Handlers me) {}
/**
* Find the names of beans annotated with
* @param me Routes
*/
public static void findAnnotatedBeans(Routes me) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(JFinal.me().getServletContext());
Map<String, Controller> controllerMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, Controller.class);
for (Controller controller : controllerMap.values()) {
Class<? extends Controller> controllerClass = controller.getClass();
WxMsgController wxController = AnnotationUtils.findAnnotation(controllerClass, WxMsgController.class);
if (wxController != null) {
me.add(wxController.value(), controllerClass);
}
}
}
}
package net.dreamlu.weixin.config;
import com.jfinal.core.Controller;
import com.jfinal.core.ControllerFactory;
import com.jfinal.core.JFinal;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringControllerFactory extends ControllerFactory {
private final ApplicationContext applicationContext;
public SpringControllerFactory() {
this.applicationContext = WebApplicationContextUtils.getWebApplicationContext(JFinal.me().getServletContext());
}
@Override
public Controller getController(Class<? extends Controller> controllerClass) throws InstantiationException, IllegalAccessException {
return applicationContext.getBean(controllerClass);
}
}
package net.dreamlu.weixin.config;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.WxaConfigKit;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.springframework.beans.factory.InitializingBean;
import java.util.List;
public class WeixinAppConfig implements InitializingBean {
private final DreamWeixinProperties weixinProperties;
public WeixinAppConfig(DreamWeixinProperties weixinProperties) {
this.weixinProperties = weixinProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
boolean isdev = weixinProperties.isDevMode();
ApiConfigKit.setDevMode(isdev);
List<ApiConfig> list = weixinProperties.getWxConfigs();
for (ApiConfig apiConfig : list) {
ApiConfigKit.putApiConfig(apiConfig);
}
WxaConfig wxaConfig = weixinProperties.getWxaConfig();
WxaConfigKit.setDevMode(isdev);
WxaConfigKit.setWxaConfig(wxaConfig);
}
}
package net.dreamlu.weixin.properties;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.wxaapp.WxaConfig;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
@ConfigurationProperties("dream.weixin")
public class DreamWeixinProperties {
/**
* JFinal filter拦截的路由
*/
@Getter
@Setter
private String urlPatterns = "/weixin/*";
/**
* 是否开发模式
*/
@Getter
@Setter
private boolean devMode = false;
/**
* accessTokenCache
* Spring cache name
*/
@Getter
@Setter
private String accessTokenCache = "dreamWeixinCache";
@Getter
@Setter
private String appIdKey = "appId";
@Getter
private List<ApiConfig> wxConfigs = new ArrayList<ApiConfig>();
@Getter
@Setter
private WxaConfig wxaConfig = new WxaConfig();
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-weixin-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>spring-boot-starter-weixin</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.example.demo;
import net.dreamlu.weixin.annotation.EnableWeixin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableWeixin
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import net.dreamlu.weixin.annotation.WxApi;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@WxApi
public class WeixinApiController {
@GetMapping("menu")
@ResponseBody
public String getMenu() {
ApiResult apiResult = MenuApi.getMenu();
return apiResult.getJson();
}
}
package com.example.demo;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import net.dreamlu.weixin.annotation.WxMsgController;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.springframework.beans.factory.annotation.Autowired;
@WxMsgController("/weixin/wx")
public class WeixinController extends MsgControllerAdapter {
@Autowired
private DreamWeixinProperties weixinProperties;
@Override
protected void processInFollowEvent(InFollowEvent inFollowEvent) {
OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
outMsg.setContent("关注消息~");
render(outMsg);
}
@Override
protected void processInTextMsg(InTextMsg inTextMsg) {
System.out.println(weixinProperties.getWxaConfig().getAppId());
OutTextMsg outMsg = new OutTextMsg(inTextMsg);
outMsg.setContent("文本消息~");
render(outMsg);
}
@Override
protected void processInMenuEvent(InMenuEvent inMenuEvent) {
OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
outMsg.setContent("菜单消息~");
render(outMsg);
}
}
dream:
weixin:
dev-mode: true
wx-configs:
- appId: wx9803d1188fa5fbda
appSecret: db859c968763c582794e7c3d003c3d87
- appId: wxc03edcd008ad1e70
appSecret: 11ed9e2b8e3e3c131e7be320a42b2b5a
token: 123456
wxa-config:
appid: wx4f53594f9a6b3dcb
appSecret: eec6482ba3804df05bd10895bace0579
\ No newline at end of file
package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册