IDEA 全稱 IntelliJ IDEA,是java編程語言開發(fā)的集成環(huán)境。IntelliJ在業(yè)界被公認為最好的java開發(fā)工具,尤其在智能代碼助手、代碼自動提示、重構(gòu)、JavaEE支持、各類版本工具(git、svn等)、JUnit、CVS整合、代碼分析、 創(chuàng)新的GUI設(shè)計等方面的功能可以說是超常的。
Maven 是一款基于 Java 平臺的項目管理和整合工具,它將項目的開發(fā)和管理過程抽象成一個項目對象模型(POM)。開發(fā)人員只需要做一些簡單的配置,Maven 就可以自動完成項目的編譯、測試、打包、發(fā)布以及部署等工作。
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上創(chuàng)建 Maven 項目
?? New Project -> Project Type: Maven -> Project SDK: 1.8 -> select maven-archtype-quickstart: Next
?????? Name: MavenQuickstart
?????? GroupId: com.example
?????? ArtifactId: MavenQuickstart
?? -> Finish
??? 1) 生成的項目目錄結(jié)構(gòu)
? ??? ??? |-- 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. 導(dǎo)入 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. 數(shù)據(jù)庫和表
?? 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 里不包含依賴的包(要手動配置依賴環(huán)境),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 里不包含依賴的包(要手動配置依賴環(huán)境),MavenQuickstart-1.0-SNAPSHOT.jar? 包含依賴包,可以直接運行。