基于gradle构建java应用程序

2018年6月30日 23:33

 
基于gradle构建java应用程序示例
 

目录

你需要什么
用户手册
初始项目
项目结构
编译项目
运行项目
总结
源码
 

你需要什么

  • 大约8分钟
  • 一个文本编辑器
  • 命令行终端
  • jdk1.7或更高版本
  • 最近版本的gradle

用户手册

gradle带有内置的init插件。它的文档地址
这个插件有一个task,名叫init,可以生成项目. init task使用内置的wrapper task生成wrapper脚本gradlew
 
运行init task
gradle init --type <name>
参数name可选值
  • java-application
  • java-library
  • scala-library
  • groovy-library
  • basic
这里我们选择java-application类型
 
首先创建项目目录
$ mkdir java-demo
$ cd java-demo
 

初始化项目

在项目目录中运行init task,并使用参数java-application
$ gradle init --type java-application
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :wrapper
> Task :init

BUILD SUCCESSFUL
 
init task先运行wrapper task生成gradlew、gradlew.bat脚本,并创建下面的项目结构
├── build.gradle
├── gradle            #wrapper的文件
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java        #源文件
    │       └── App.java
    └── test            #测试
        └── java
            └── AppTest.java
 
 

项目结构

settings.gradle有很多注释,有效行只有一行
settings.gradle
rootProject.name='java-demo'
配置root project的名称java-demo
 
生成的build.gradle同样有很多注释,下面是有效部分
build.gradle
apply plugin: 'java'
apply plugin: 'application'

repositories {
    jcenter()      #公有仓库
}

dependencies {
    compile 'com.google.guava:guava:21.0'   #google的guava包
    testCompile 'junit:junit:4.12'          #junit测试包
}

mainClassName = 'App'    #main类
build文件中加了java和application两个插件。前者支持java项目,后者允许指定包含main方法的类,在编译时执行
 
src/main/App.java
public class App {
    public String getGreeting() {
        return "Hello world.";
    }

    public static void main(String[] args) {   #在运行application插件的run task时调用
        System.out.println(new App().getGreeting());
    }
}
 
src/test/java/AppTest.java
import org.junit.Test;
import static org.junit.Assert.*;

public class AppTest {
    @Test public void testAppHasAGreeting() {
        App classUnderTest = new App();
        assertNotNull("app should have a greeting",
            classUnderTest.getGreeting());
    }
}
 
编译项目
编译项目使用build命令。可以使用常用的gradle命令,但是使用wrapper脚本更好
$ ./gradlew build
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :jar
> Task :startScripts
> Task :distTar
> Task :distZip
> Task :assemble
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses

> Task :test

> Task :check
> Task :build

BUILD SUCCESSFUL
注意:第一次运行时会比较慢
 
第一次运行build时,会检查.gradle目录是否存在guava、junit包。如果不存在,则下载并存到本地目录
下次运行build就使用缓存。build task编译class文件,运行test用例,生成测试报告
 
查看html报告build/reports/tests/test/index.html.
样例
 

运行项目

gradle构建使用了application插件,所以能在命令行运行程序。
看看有哪些task
$ ./gradlew tasks
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

// ... many other tasks ...
 
run task会让gradle读取mainClassName属性指定的类,执行main方法
$ ./gradlew run
:compileJava UP-TO-DATE
:processResources NO-SOURCE
:classes UP-TO-DATE
:run
Hello world.


BUILD SUCCESSFUL
 

总结

通过上面介绍可以学到
  • 如何生成java应用程序
  • 如何生成build文件、java文件
  • 如何运行构建、查看测试报告
  • 如何使用application插件的run task执行程序

源码

github地址
 
参考资料
 
了凡四训》详解之改过之法
印光大师十念法(胡小林主讲第1集)

 

Tags: gradle
评论(12) 阅读(2116)

debian中设置tomcat开机启动

2015年3月11日 16:57

  • 解压  
在tomcat的bin目录下有commons-daemon-native.tar.gz文件
➜  bin  tar -zxvf commons-daemon-native.tar.gz
  • 编译
➜  unix  ./configure 
...
➜  unix  make
  • 复制到bin目录  
编译后生成jsvc文件,复制到bin目录下
cp jsvc /home/wyq/software/apache-tomcat-7.0.59/bin/
  • 设置启动用户
打开daemon.sh文件,默认用户是tomcat,可以自己更改
TOMCAT_USER=wyq
  • 启动/停止
sh daemon.sh start/stop
  • 修改daemon.sh配置
在daemon.sh文件中添加以下配置
pkenv=/home/wyq/pkenv
JAVA_HOME=$pkenv/jdk1.7.0_75
CATALINA_HOME=$pkenv/apache-tomcat-7.0.59
CATALINA_BASE=$pkenv/apache-tomcat-7.0.59
DAEMON_HOME=$pkenv/apache-tomcat-7.0.59/bin
TOMCAT_USER=wyq
  • 添加到/etc/init.d
cd /etc/init.d
ln -s xxxx/bin/daemon.sh tomcat
  • 以service方式启动/停止
sudo service tomcat start/stop
重启机器,tomcat会跟随启动启动.
 

Tags: tomcat
评论(108) 阅读(4879)

一台机器部署多个tomcat

2015年3月11日 14:02

修改conf/server.xml文件中的三个端口
8005 用于停止Tomcat的端口
8009 Apache的侦听端口
8080 默认的连接端口
 

Tags: tomcat
评论(3) 阅读(2865)

在运行jetty-maven-plugin时,出现错误

2015年1月13日 10:22

在运行jetty-maven-plugin出现错误
 
[ERROR] Failed to execute goal org.eclipse.jetty:jetty-maven-plugin:9.2.6.v20141205:run (default-cli) on project PKPlatform_web: Execution default-cli of goal org.eclipse.jetty:jetty-maven-plugin:9.2.6.v20141205:run failed: Unable to load the mojo 'run' in the plugin 'org.eclipse.jetty:jetty-maven-plugin:9.2.6.v20141205' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/eclipse/jetty/maven/plugin/JettyRunMojo : Unsupported major.minor version 51.0
[ERROR] -----------------------------------------------------
[ERROR] realm =    plugin>org.eclipse.jetty:jetty-maven-plugin:9.2.6.v20141205
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-maven-plugin/9.2.6.v20141205/jetty-maven-plugin-9.2.6.v20141205.jar
[ERROR] urls[1] = file:/D:/DEV/mavenRepons/org/sonatype/sisu/sisu-inject-bean/2.1.1/sisu-inject-bean-2.1.1.jar
[ERROR] urls[2] = file:/D:/DEV/mavenRepons/org/sonatype/sisu/sisu-guice/2.9.4/sisu-guice-2.9.4-no_aop.jar
[ERROR] urls[3] = file:/D:/DEV/mavenRepons/org/codehaus/plexus/plexus-utils/2.0.6/plexus-utils-2.0.6.jar
[ERROR] urls[4] = file:/D:/DEV/mavenRepons/org/sonatype/aether/aether-util/1.11/aether-util-1.11.jar
[ERROR] urls[5] = file:/D:/DEV/mavenRepons/org/codehaus/plexus/plexus-interpolation/1.14/plexus-interpolation-1.14.jar
[ERROR] urls[6] = file:/D:/DEV/mavenRepons/org/codehaus/plexus/plexus-component-annotations/1.5.5/plexus-component-annotations-1.5.5.jar
[ERROR] urls[7] = file:/D:/DEV/mavenRepons/org/sonatype/plexus/plexus-sec-dispatcher/1.3/plexus-sec-dispatcher-1.3.jar
[ERROR] urls[8] = file:/D:/DEV/mavenRepons/org/sonatype/plexus/plexus-cipher/1.4/plexus-cipher-1.4.jar
[ERROR] urls[9] = file:/D:/DEV/mavenRepons/org/apache/maven/plugin-tools/maven-plugin-tools-api/3.1/maven-plugin-tools-api-3.1.jar
[ERROR] urls[10] = file:/D:/DEV/mavenRepons/backport-util-concurrent/backport-util-concurrent/3.1/backport-util-concurrent-3.1.jar
[ERROR] urls[11] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-util/9.2.6.v20141205/jetty-util-9.2.6.v20141205.jar
[ERROR] urls[12] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-webapp/9.2.6.v20141205/jetty-webapp-9.2.6.v20141205.jar
[ERROR] urls[13] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-xml/9.2.6.v20141205/jetty-xml-9.2.6.v20141205.jar
[ERROR] urls[14] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-servlet/9.2.6.v20141205/jetty-servlet-9.2.6.v20141205.jar
[ERROR] urls[15] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-quickstart/9.2.6.v20141205/jetty-quickstart-9.2.6.v20141205.jar
[ERROR] urls[16] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-jaas/9.2.6.v20141205/jetty-jaas-9.2.6.v20141205.jar
[ERROR] urls[17] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-security/9.2.6.v20141205/jetty-security-9.2.6.v20141205.jar
[ERROR] urls[18] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-plus/9.2.6.v20141205/jetty-plus-9.2.6.v20141205.jar
[ERROR] urls[19] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-jndi/9.2.6.v20141205/jetty-jndi-9.2.6.v20141205.jar
[ERROR] urls[20] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-server/9.2.6.v20141205/jetty-server-9.2.6.v20141205.jar
[ERROR] urls[21] = file:/D:/DEV/mavenRepons/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar
[ERROR] urls[22] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-http/9.2.6.v20141205/jetty-http-9.2.6.v20141205.jar
[ERROR] urls[23] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-io/9.2.6.v20141205/jetty-io-9.2.6.v20141205.jar
[ERROR] urls[24] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-jmx/9.2.6.v20141205/jetty-jmx-9.2.6.v20141205.jar
[ERROR] urls[25] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/jetty-annotations/9.2.6.v20141205/jetty-annotations-9.2.6.v20141205.jar
[ERROR] urls[26] = file:/D:/DEV/mavenRepons/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar
[ERROR] urls[27] = file:/D:/DEV/mavenRepons/org/ow2/asm/asm/5.0.1/asm-5.0.1.jar
[ERROR] urls[28] = file:/D:/DEV/mavenRepons/org/ow2/asm/asm-commons/5.0.1/asm-commons-5.0.1.jar
[ERROR] urls[29] = file:/D:/DEV/mavenRepons/org/ow2/asm/asm-tree/5.0.1/asm-tree-5.0.1.jar
[ERROR] urls[30] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/javax-websocket-server-impl/9.2.6.v20141205/javax-websocket-server-impl-9.2.6.v20141205.jar
[ERROR] urls[31] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/javax-websocket-client-impl/9.2.6.v20141205/javax-websocket-client-impl-9.2.6.v20141205.jar
[ERROR] urls[32] = file:/D:/DEV/mavenRepons/javax/websocket/javax.websocket-api/1.0/javax.websocket-api-1.0.jar
[ERROR] urls[33] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/websocket-server/9.2.6.v20141205/websocket-server-9.2.6.v20141205.jar
[ERROR] urls[34] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/websocket-common/9.2.6.v20141205/websocket-common-9.2.6.v20141205.jar
[ERROR] urls[35] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/websocket-api/9.2.6.v20141205/websocket-api-9.2.6.v20141205.jar
[ERROR] urls[36] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/websocket-client/9.2.6.v20141205/websocket-client-9.2.6.v20141205.jar
[ERROR] urls[37] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/websocket/websocket-servlet/9.2.6.v20141205/websocket-servlet-9.2.6.v20141205.jar
[ERROR] urls[38] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/apache-jsp/9.2.6.v20141205/apache-jsp-9.2.6.v20141205.jar
[ERROR] urls[39] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/toolchain/jetty-schemas/3.1.M0/jetty-schemas-3.1.M0.jar
[ERROR] urls[40] = file:/D:/DEV/mavenRepons/org/mortbay/jasper/apache-jsp/8.0.9.M3/apache-jsp-8.0.9.M3.jar
[ERROR] urls[41] = file:/D:/DEV/mavenRepons/org/mortbay/jasper/apache-el/8.0.9.M3/apache-el-8.0.9.M3.jar
[ERROR] urls[42] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/orbit/org.eclipse.jdt.core/3.8.2.v20130121/org.eclipse.jdt.core-3.8.2.v20130121.jar
[ERROR] urls[43] = file:/D:/DEV/mavenRepons/org/eclipse/jetty/apache-jstl/9.2.6.v20141205/apache-jstl-9.2.6.v20141205.jar
[ERROR] urls[44] = file:/D:/DEV/mavenRepons/org/apache/taglibs/taglibs-standard-spec/1.2.1/taglibs-standard-spec-1.2.1.jar
[ERROR] urls[45] = file:/D:/DEV/mavenRepons/org/apache/taglibs/taglibs-standard-impl/1.2.1/taglibs-standard-impl-1.2.1.jar
[ERROR] urls[46] = file:/D:/DEV/mavenRepons/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import  from realm ClassRealm[maven.api, parent: null]]
[ERROR] 
[ERROR] -----------------------------------------------------
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException
 
从上面发现
repository.exception.ComponentLookupException: org/eclipse/jetty/maven/plugin/JettyRunMojo : Unsupported major.minor version 51.0
很明显是版本问题. 检查jdk,版本是1.6,改为1.7后,重新运行,一切正常.
 

Tags: jetty
评论(16) 阅读(22967)

jetty-maven-plugin静态文件保存不了

2014年12月31日 11:08

起因

为maven项目配置jetty-maven-plugin插件,以jetty:run方式运行,会出现静态文件保存不了的问题。原因是jetty内存映射文件来缓存静态文件. 解决方法是将jetty内存映射参数取消掉.

解决

找webdefault.xml文件

在下面路径找到webdefault.xml文件
C:\Users\Administrator\.m2\repository\org\eclipse\jetty\jetty-webapp\9.2.6.v20141205
如果安装了jetty服务器,在它的etc目录下也可以取到webdefault.xml文件

useFileMappedBuffer参数值改为false

webdefault.xml配置
<init-param>
  <param-name>useFileMappedBuffer</param-name>
  <param-value>false</param-value>
</init-param>

新增defaultsDescriptor配置项

<plugin>  
    <groupId>org.eclipse.jetty</groupId>  
    <artifactId>jetty-maven-plugin</artifactId>  
    <version>9.2.6.v20141205</version>  
    <configuration>
        <scanIntervalSeconds>0</scanIntervalSeconds>
        <webAppSourceDirectory>${basedir}/WebRoot</webAppSourceDirectory>
        <webApp>  
            <contextPath>/</contextPath>
            <war>${project.build.directory}/${project.build.finalName}.war</war>
            <!-- jetty9.2.6的defaultsDescriptor在<webApp>里,早期版本在<configuration>或者<webAppConfig>里 -->
            <defaultsDescriptor>${basedir}/WebRoot/resources/webdefault.xml</defaultsDescriptor>
        </webApp> 
</configuration>
</plugin>

webdefault.xml加载是否成功

控制台输出如下,表示加载了webdefualt.xml
[INFO] Web defaults = .... /WebRoot/resources/webdefault.xml

感受

上面方法虽然可以解决问题,但是很不好用. 如果jetty-maven-plugin能设计个开发模式设置,在易用性上会有更大提升.

参考资料

jetty-maven-plugin配置文档
maven文档
 
 

评论(413) 阅读(49732)

第一个jetty程序

2014年11月21日 17:36

  • 下载
  • 新建root目录
解压之后在webapps下新建root目录
  • 新建index.jsp文件
在root目录中新建index.jsp文件
<html>
<body>
<%
    out.println("hello world")
%>
</body>
</html>
  • 启动
进入控制台运行
java -jar start.jar
 
在windows下可能出现下面错误,原因是执行java命令时优先使用windows自带的java,但是lib却使用我们配置的classpath.
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
....
 
解决办法
C:\Program" "Files\Java\jdk1.7.0_60\bin\java -jar start.jar
  • 访问
http://localhost:8080 即可看到hello word
 

Tags: jetty
评论(3) 阅读(3949)

JSTL日期格式化

2014年11月06日 12:18

引入标签库

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

用法

<fmt:formatDate value="${DATE}"    pattern="yyyy-MM-dd HH:mm:ss" type="date" dateStyle="long" /> 
 

Tags: jsp
评论(0) 阅读(1662)

forEach迭代列表与整数

2014年11月06日 11:18

整数迭代

<!-- 简单示例 -->
<c:forEach var="i" begin="1" end="10" step="1"> 
    <c:out value="${i}" />
</c:forEach>

<!-- 传入变量 -->
<c:forEach var="i" begin="1" end="$(totalPage)" step="1"> 
    <c:out value="${i}" />
</c:forEach>

列表迭代

<!-- experts是个List<Map>-->
<c:forEach items="${experts}" var="expert" varStatus="status" begin="0" end="9">
    <tr>
    <td>${status.index+1}</td>
    <td><img src="${expert.headImagePath}"/></td>
    <td>${expert.expertName}</td>
    <td>${expert.phone}</td>
    <td>${expert.address}</td>
    <td>${expert.expertIntroduction}</td>
    <td>${expert.createTime}</td>
    <td data-expertid="${expert.expertID}">
    </tr>
</c:forEach>

参数说明

items 被迭代的列表(迭代整数时不用设置)
begin 开始的元素(0=第一个元素,1=第二个元素)
end最后一个元素(0=第一个元素,1=第二个元素)
step每次迭代的步长
var 当前条目的变量名称
varStatus 循环状态的变量名称(可以获取序列号)
 

Tags: jstl;迭代
评论(10) 阅读(2534)