2021-12-16 IDEA创建Maven Quickstart项目

IDEA 全称 IntelliJ IDEA,是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能可以说是超常的。

Maven 是一款基于 Java 平台的项目管理和整合工具,它将项目的开发和管理过程抽象成一个项目对象模型(POM)。开发人员只需要做一些简单的配置,Maven 就可以自动完成项目的编译、测试、打包、发布以及部署等工作。

OS:macOS High Sierra (Version: 10.13.6)

IDEA:IntelliJ IDEA 2020.1.4 (Community Edition)

Database: MariaDB 10.1.13 (MariaDB是MySQL源代码的一个分支)

1. 安装 Java 8+

    $ java -version

    openjdk version "1.8.0_302"
    OpenJDK Runtime Environment Corretto-8.302.08.1 (build 1.8.0_302-b08)
    OpenJDK 64-Bit Server VM Corretto-8.302.08.1 (build 25.302-b08, mixed mode)


2. 安装 Maven 3.8.1

    https://maven.apache.org/

    $ wget https://mirrors.bfsu.edu.cn/apache/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz

    $ mv ./apache-maven-3.8.1-bin.tar.gz ~/Applications/java/   # 移动到你想要放置的文件夹
    $ tar -zvxf apache-maven-3.8.1-bin.tar.gz       # ~/Applications/java/apache-maven-3.8.1

    $ sudo vim /etc/profile

        # Add JAVA_HOME ...
        JAVA_HOME=/Users/xxx/Library/Java/JavaVirtualMachines/corretto-1.8.0_302/Contents/Home
        JRE_HOME=$JAVA_HOME/jre
        CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
        PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin:/Users/xxx/Applications/java/apache-maven-3.8.1/bin
        export JAVA_HOME JRE_HOME CLASS_PATH PATH
    
    $ source /etc/profile

    $ vim ~/Applications/java/apache-maven-3.8.1/conf/settings.xml

        ...
        # 修改本地仓库路径
        <localRepository>/Users/xxx/Applications/Java/maven-repository</localRepository>

        ...
        # 修改成阿里源
        <mirror>
          <id>alimaven</id>
          <name>aliyun maven</name>
          <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
          <mirrorOf>central</mirrorOf>       
        </mirror>


3. 安装 IntelliJ Idea

      下载 https://www.jetbrains.com/idea/download/download-thanks.html?platform=mac&code=IIC

      Mac OS: ideaIC-2020.1.dmg
      Windows: ideaIC-2020.1.exe


      运行 Idea 并配置:

      IntelliJ IDEA -> Preferences -> Build, Execution, Deployment -> Build Tools -> Maven

          Maven home path: ~/Applications/java/apache-maven-3.8.1
          User settings file: ~/Applications/java/apache-maven-3.8.1/conf/settings.xml
          Local repository: ~/Applications/java/maven-repository


4. 在 IDEA上创建 Maven 项目

   New Project -> Project Type: Maven -> Project SDK: 1.8 -> select maven-archtype-quickstart: Next

       Name: MavenQuickstart

       GroupId: com.example

       ArtifactId: MavenQuickstart

   -> Finish

    1) 生成的项目目录结构

          |-- src
          |   |-- main
          |   |     |-- java
          |   |       |-- com
          |   |               |-- example
          |   |                     |-- App.java
          |   |-- test
          |        |-- java
          |               |-- com
          |                    |-- example
          |                         |-- AppTest.java
          |-- pom.xml

     2) App.java

        package com.example;

        public class App {

            public static void main( String[] args ) {

                System.out.println( "Hello World!" );

            }

        }


5. 编译和运行

    在IDE中项目列表  External Libraries -> <1.x> -> Open Library Settings -> Platform Settings -> SDKS

        Name: 1.8

        JDK home path: select 1.8 SDK or download a SDK

        1) Run App.main()

            Open App.java, click mouse right button, select Run "App.main()"

        2) Edit Configurations

            Click "+" add new configuration -> Select "Application"

                Name: MaventQuickstart

                Main class: com.example.App

            -> Apply / OK

        Click Run "MavenQuickstart"


6. 导入 MariaDB, log4j (非必选)

      访问 http://www.mvnrepository.com/,查询 MariaDB, log4j

      修改 pom.xml

        <project ... >

            ...

                <dependencies>

                    ...

                    <!-- https://mvnrepository.com/artifact/log4j/log4j -->

                    <dependency>

                      <groupId>log4j</groupId>

                      <artifactId>log4j</artifactId>

                      <version>1.2.17</version>

                    </dependency>

                    <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->

                    <dependency>

                      <groupId>org.mariadb.jdbc</groupId>

                      <artifactId>mariadb-java-client</artifactId>

                      <version>2.7.4</version>

                    </dependency>

                     ...

                </dependencies>

            ...

        </project>

        在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project


7. 支持 log4j (非必选)

    添加 src/main/resources/log4j.properties

        # Define the root logger with appender file
        log4j.rootLogger = DEBUG, FILE

        # Define the file appender
        log4j.appender.FILE=org.apache.log4j.FileAppender
        # Set the name of the file
        log4j.appender.FILE.File=/Users/xxx/logs/maven-quickstart_log4j.txt

        # Set the immediate flush to true (default)
        log4j.appender.FILE.ImmediateFlush=true

        # Set the threshold to debug mode
        log4j.appender.FILE.Threshold=debug

        # Set the append to false, overwrite
        log4j.appender.FILE.Append=false

        # Define the layout for file appender
        log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
        log4j.appender.FILE.layout.conversionPattern=%m%n       


8. 数据库和表

   1) MySQL/MariaDB

     Database Name: testdb

     User: root

     Password: 123456

     SQL:

       CREATE TABLE `user` (

        `id` int(11) NOT NULL AUTO_INCREMENT,

        `name` varchar(50) NOT NULL,

        `password` varchar(255) DEFAULT NULL,

        `age` int(11) DEFAULT NULL,

        `createtime` timestamp NULL DEFAULT NULL,

        PRIMARY KEY (`id`)

       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    2) Add src/main/resources/config.properties

        # Database Config
        db_driverClassName=org.mariadb.jdbc.Driver
        db_url=jdbc:mysql://localhost/testdb?characterEncoding=utf8
        db_username=root
        db_password=123456

    3) 添加 src/main/java/com/example/entity/User.java

            package com.example.entity;

            import java.text.SimpleDateFormat;
            import java.util.Date;

            public class User {
                private int id;
                private String name;
                private String password;
                private int age;
                private Date createtime;

                public User() {

                }

                public int getId() {
                    return id;
                }

                public void setId(int id) {
                    this.id = id;
                }

                public String getName() {
                    return this.name;
                }

                public void setName(String name) {
                    this.name = name;
                }

                public String getPassword() {
                    return password;
                }

                public void setPassword(String password) {
                    this.password = password;
                }

                public int getAge() {
                    return this.age;
                }

                public void setAge(int age) {
                    this.age = age;
                }

                public Date getCreatetime() {
                    return this.createtime;
                }

                public void setCreatetime(Date createtime) {
                    this.createtime = createtime;
                }

                @Override
                public String toString() {
                    String strCreateTime = "";
                    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (createtime != null)
                        strCreateTime = f.format(createtime);

                    return "id: " + id + ", name: " + name + ", age: " + age +  ", createtime: " + strCreateTime;
                }

            }

    4) 添加 src/main/java/com/example/DemoJDBC.java

        package com.example;

        import java.io.IOException;
        import java.io.InputStream;
        import java.util.Properties;
        import java.util.Date;
        import java.text.SimpleDateFormat;

        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.ResultSet;
        import java.sql.PreparedStatement;
        import java.sql.SQLException;

        import com.example.App;

        public class DemoJdbc {
            private  String strName = "jdbcUser";
            private  String strConfig = "/config.properties";

            public void runDB() {

                App.log.info("DemoJdbc -> runDB()");

                try {

                    // Read config file
                    InputStream resStream = this.getClass().getResourceAsStream(strConfig);
                    Properties properties = new Properties();
                    properties.load(resStream);

                    String strDriverName =  properties.getProperty("db_driverClassName");
                    String strUrl =  properties.getProperty("db_url");
                    String strUsername =  properties.getProperty("db_username");
                    String strPassword =  properties.getProperty("db_password");
                    System.out.println("db_driverClassName: " + strDriverName);

                    //
                    System.out.println("Connecting to MariaDB ...");
                    Class.forName(strDriverName);
                    Connection conn = DriverManager.getConnection(strUrl, strUsername, strPassword);

                    String strSql = "SELECT * FROM user WHERE name = ?";
                    PreparedStatement ps = conn.prepareStatement(strSql);
                    ps.setString(1, strName);
                    ResultSet rs = ps.executeQuery();

                    if(rs.next()) {
                        System.out.println("Name = " + rs.getString("name"));

                    } else {

                        strSql = "INSERT INTO user (name, password, age, createtime) values (?, ?, ?, ?)";
                        PreparedStatement ps2 = conn.prepareStatement(strSql);
                        ps2.setString(1, strName);
                        ps2.setString(2, "123456");
                        ps2.setInt(3, 25);
                        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        ps2.setString(4, f.format(new Date()));

                        int ret = ps2.executeUpdate();
                        if (ret > 0) {
                            System.out.println("Add '" + strName + "' to database successfully, ret = " + ret);

                        } else {
                            System.out.println("Add '" + strName + "' to database failed, ret = " + ret);

                        }
                    }

                } catch (ClassNotFoundException err) {
                    err.printStackTrace();

                } catch (SQLException err2) {
                    err2.printStackTrace();

                } catch (IOException err3) {
                    err3.printStackTrace();

                } catch (Exception err4) {
                    err4.printStackTrace();

                }
            }
        }

    5) 修改 src/main/java/com/example/App.java

        package com.example;

        import org.apache.log4j.Logger

        public class App {

            public static Logger log = Logger.getLogger(App.class.getName());

            public static void main(String[] args) throws Exception {

                DemoJdbc demoJdbc = new DemoJdbc();

                demoJdbc.runDB();

            }

        }

    运行步骤 5, 编译和运行


9. 打包 jar

    以下三种打包方法独立使用,pom.xml 里同一时间只存在一种方式。
   
     1) 使用 maven-jar-plugin 和 maven-dependency-plugin 插件打包

         添加/修改 pom.xml 的 build 部分:
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                                <mainClass>com.example.App</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>3.0.2</version>
                    <executions>
                        <execution>
                            <id>copy-dependencies</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    
        在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project

        View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package

        Idea -> Terminal
       
        $ java -jar target/MavenQuickstart-1.0-SNAPSHOT.jar

            Connecting to MariaDB ...
            ...

        *注:MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包,依赖包在 target/lib 目录下


    2)使用 maven-assembly-plugin 插件打包

        添加/修改 pom.xml 的 build 部分:
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>com.example.App</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                    <executions>
                        <execution>
                            <id>make-assembly</id>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>   

        在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project

        View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package

        Idea -> Terminal

        $ java -jar target/MavenQuickstart-1.0-SNAPSHOT-jar-with-dependencies.jar

            Connecting to MariaDB ...
            ...

        *注:MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包(要手动配置依赖环境),MavenQuickstart-1.0-SNAPSHOT-jar-with-dependencies.jar 包含依赖包,可以直接运行。 如果项目中用到spring Framework,用这种方式打出来的包运行时可能会出错。


    3)使用 maven-shade-plugin 插件打包

        项目中用到 spring Framework, 使用这种打包方式。

        添加/修改 pom.xml 的 build 部分:
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <transformers>
                                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                        <mainClass>com.example.App</mainClass>
                                    </transformer>
                                </transformers>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>

        在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project

        View -> Tool Windows -> Maven -> MavenQuickstart -> Lifecycle -> Clean | Package

        Idea -> Terminal

        $ java -jar target/MavenQuickstart-1.0-SNAPSHOT.jar

            Connecting to MariaDB ...
            ...

        *注: original-MavenQuickstart-1.0-SNAPSHOT.jar 里不包含依赖的包(要手动配置依赖环境),MavenQuickstart-1.0-SNAPSHOT.jar  包含依赖包,可以直接运行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容