前阵子接触了Kotlin,被它的灵活与效率迷倒,然后就不太愿意写Java了。
最近尝试Leancloud云引擎使用了Java SDK,发现稍加修改即可支持纯Kotlin开发。好像没有搜到有别人这么玩过,给大家分享一下。
没听过Kotlin的同学可以先读读这篇Kotlin: Java 6 废土中的一线希望
下面直接进入正题,就改3处:
- pom配置
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
......
<dependencies>
<dependency>
<groupId>cn.leancloud</groupId>
<artifactId>leanengine</artifactId>
<version>0.1.14</version>
</dependency>
......
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.0.5</version>
</dependency>
......
</dependencies>
<build>
<plugins>
......
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>1.0.5</version>
<executions>
<execution>
<id>compile</id>
<goals> <goal>compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals> <goal>test-compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
所以工程的文件结构是这样的
-
AppInitListener.kt
package com.cpiz.loanassistant.cloud
import cn.leancloud.LeanEngine
import com.avos.avoscloud.AVOSCloud
import com.avos.avoscloud.internal.impl.JavaRequestSignImplementation
import org.apache.logging.log4j.LogManager
import javax.servlet.ServletContextEvent
import javax.servlet.ServletContextListener
import javax.servlet.annotation.WebListener
@WebListener
class AppInitListener : ServletContextListener {
private val appId = System.getenv("LEANCLOUD_APP_ID")
private val appKey = System.getenv("LEANCLOUD_APP_KEY")
private val appMasterKey = System.getenv("LEANCLOUD_APP_MASTER_KEY")
override fun contextDestroyed(arg0: ServletContextEvent) {
}
override fun contextInitialized(arg0: ServletContextEvent) {
logger.info("LeanEngine app init.")
logger.info("Environment: ${System.getenv("LEANCLOUD_APP_ENV")}")
// 初始化AVOSCloud,请保证在整个项目中间只初始化一次
LeanEngine.initialize(appId, appKey, appMasterKey)
// 在请求签名中使用masterKey以激活云代码的最高权限
JavaRequestSignImplementation.instance().setUseMasterKey(true)
// 向云引擎注册云函数
// com.cpiz.loanassistant.cloud.CloudKt即为云函数的实现
LeanEngine.register(Class.forName("com.cpiz.loanassistant.cloud.CloudKt"))
if (System.getenv("LEANCLOUD_APP_ENV") == "development") {
// 打开 debug 日志
AVOSCloud.setDebugLogEnabled(true)
// 如果是开发环境,则设置 AVCloud.callFunction 和 AVCloud.rpcFunction 调用本地云函数实现
// 如果需要本地开发时调用云端云函数实现,则注释掉下面语句。
LeanEngine.setLocalEngineCallEnabled(true)
}
}
companion object {
private val logger = LogManager.getLogger(AppInitListener::class.java)
}
}
-
com.cpiz.loanassistant.cloud.CloudKt
package com.cpiz.loanassistant.cloud
import cn.leancloud.EngineFunction
import cn.leancloud.EngineFunctionParam
import ......
/**
* 测试云函数
*/
@EngineFunction
fun hello(): String {
return "Hello world!"
}
OK,现在这就是一个纯Kotlin,没有一行Java代码的云引擎项目了