Maven Beginner's Tutorial


Learning the use of maven, I saw a very practical introductory tutorial (novice level entry)
2007-08-28 14:01:04
Label: maven workplace leisure


1. Preface
        I have long known that maven has a prominent reputation in the management of java projects. So I thought about learning to master it, so I consulted a lot of documents. I found that the authors of these documents are all big names in java, and most of them are introduced from the perspective of mastering a certain maven foundation, which makes me, a beginner, confused. So I went to check maven's official website again, and I finally understood something, but once I started the actual operation, I was confused. Alas, there is no way to do it, just try again and again, and after all
kinds of hardships, I finally have a little look. I will write down my experience now, to avoid forgetting in the future, and to provide a little convenience for novices like me. Ha ha. The theme of this article is practical operation, and the principle is still to trouble you to check the articles of the big names in java. Two articles are recommended here:


Maven 2.0:



New Features of Compiling, Testing, Deploying, Running Maven2
http://www-128.ibm.com/developerworks/cn/opensource/os-maven2/index.html




Second, maven2 installation
1 , First go to the official website to download: http://maven.apache.org/download.html , I chose the latest version of maven2.0.4 version
2, set the environment variables: After Maven2 is downloaded, I will extract it to Under d:\maven204 of my computer, the directory structure is as follows:
D:\
|--Maven204
|-- bin
|-- conf
|-- core
|-- lib
|-- local


environment variables: (operating system windows2003)
        my computer----properties----advanced----environment variables, click " New under "System Variables", enter: variable name MAVEN_HOME; variable value d:\Maven204, find the system variable path in the system variable list, open it, and append ";%MAVEN_HOME%\bin" to the variable value, so far the environment variable Setup is complete.
        Check whether the installation has been completed, open the dos window, enter mvn -v, if the following message appears, it means that maven2 has been installed successfully:
X:> mvn -v
Maven Version 2.0.4


I have said enough details, still not? Then I can only say that you are better than me.



3. Create the first java project with maven2
1. Select a root directory, my java working directory is D:\eclipse\workspace
2. Open the dos window and use the cd command to enter the D:\eclipse\workspace directory
3. Enter the following Command
D:\eclipse\workspace>mvn archetype:create -DgroupId=com.efn -DartifactId=study
After the command is executed, the following directory structure will appear:
study
|-- pom.xml
`-- src
|-- main
| `-- java
| `-- com
| `-- mycompany
| `-- app
| `-- App.java
`-- test
`-- java
`-- com
`-- mycompany
`-- app
`-- AppTest.java


Fourth, generate eclipse project file
I use the development tool is eclipse, so use maven's eclipse parameter to generate eclipse project file. Enter the following
1. Use the cd command of dos to enter the study directory
2. Enter the command: mvn eclipse:eclipse as shown below:
D:\eclipse\workspace\study>mvn eclipse:
After the eclipse command is executed, two more files are found: .classpath and .project


5. Download maven's eclipse plugin
1. Open eclipse
2. Open the menu help -Software updates-Find and Install
3. Select the second item and go to the next step
4. Click the button "New Remote Site..."
5. Enter in Name: Maven2, enter in URL http://m2eclipse.codehaus.org/
Ok, now everything is automated, all you need to do is wait and press the button when prompted.


6. Import the project The project file of eclipse has been generated
just now , and now it is imported. Menu File-import, press "Next", select the project file after the import is completed, the project management perspective will appear the study node, on the project node, press the right mouse button to open the pop-up menu, select the maven2 menu item, and pop up a submenu ->Enable, click to open, enter: study in Group Id.


Open the pom.xml file of the study, there will be content similar to the following:




xml code
1.
<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/maven-v4_0_0.xsd "> 

2.
  <modelVersion> 4.0.0</modelVersion> 

3.
  <groupId>com.efn</groupId> 

4.
  <artifactId>study</artifactId> 

5.


6.
  <version>1.0-SNAPSHOT</version> 

7.
  <name>Maven Quick Start Archetype</name> 

8.
  <url> http://maven.apache.org </url> 

9.
</project> 



NOTE : The role of this file and the role of each node is not the focus of this article. You can go to the official website of maven to check http://maven.apache.org/ So far, all the preparations have been completed, and now we will use a The main main function accesses the database as an example to introduce its use in actual development.


7. Build a rack package
Every java project inevitably uses a third-party rack package. The advantage of Maven is that it can manage these rack packages in a unified manner, and allow multiple java projects to share these rack packages. All we need to do is edit the pom.xml file according to the rules. Maven is already very smart. Using the wizard of maven's eclipse plug-in, the configuration file can be generated as long as the parameters are input. Our example is to use jdbc to access oracle's database. So it needs the support of jdbc and oracle's rack package. Next, we will build these two rack packages into the study project.


There are two ways to use:
1. Automatic wizard
The first is to use the wizard mode and let the wizard go directly to the maven server to download the shelf package you need. This method has certain risks. First, there may not be what you need on the maven server. Second, every time Smart maven is always looking for stuff that doesn't exist. Throwing out a lot of red-letter prompts is depressing. However, in order to ensure the integrity of the document, the steps are given. Take junit as an example (there is no problem with this stuff, huh, huh) When the maven of the project is enabled, the maven2 sub-menu of the menu pops up, select the "Add Dependency" menu item of the sub-menu, and enter "junit" in the Query, the wizard will Automatically lists related lists for selection. Select the shelf package you need most and press the "OK" button.
If the shelf package already exists in your local repository, the wizard only adds dependency information in pom.xml. The content of the pom.xml file is as follows:

xml code
1.
<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/maven-v4_0_0.xsd> 

2.
<modelVersion>4.0.0</modelVersion> 

3.
<groupId>com.efn</groupId> 

4.


5.
<packaging>jar</packaging> 

6.
<version>1.0-SNAPSHOT</version> 

7.
<name>Maven Quick Start Archetype</name> 

8.
<url> http://maven.apache.org </url> 

9.
<dependencies> 

10.
<dependency> 

11.
<groupId>junit</groupId> 

12.
<artifactId>junit</artifactId> 

13.
<version>3.8.1</version> 

14.
</dependency> 

15.
</dependencies> 

16.
</project>  06-8-4 09:21:07: Local repository folder "" does not exist


If the local repository does not exist, the wizard will go to the maven server to download the shelf package, and output the download log in the console as follows:

06-8-4 9:21:11AM: Reading /study/pom.xml
06-8-4 9:21:11AM: Local repository folder "" does not exist
06-8-4 9:21AM min 18 sec: Reading /study/pom.xml 06-8-4
9:21:18 am: Local repository folder "" does not exist
06-8-4 9:21:19 am: Reading /study/pom .xml
06-8-4 9:21:19 AM: Local repository folder "" does not exist
06-8-4 9:36:33 AM: Local repository folder "" does not exist
06-8-4 AM 09:37:11: Reading / study /pom.xml
06-8-4 09:37:11: Local repository folder "" does not exist
06-8-4 09:37:15: Local repository folder "" does not exist
06-8-4 09:40:07AM: Local repository folder "" does not exist
06-8-4 09:40:08AM: Reading / study /pom. xml
06-8-4 9:40:08AM: Local repository folder "" does not exist
06-8-4 9:46:24AM: Reading / study /pom.xml
06-8-4 9:46AM minute 24 seconds: Local repository folder "" does not exist
06-8-4 09:46:28 am: Local repository folder "" does not exist
06-8-4 9:46:40 am: Local repository folder " " does not exist
06-8-4 9:46:47 AM: Local repository folder "" does not exist
06-8-4 09:46:47 AM: Reading / study /pom.xml
06-8-4 09:46:47AM : Local repository folder "" does not exist
06-8-4 09:46:49AM: Downloading [central] -> http://repo1.maven.org/maven2/junit/junit /3.8.1/junit-3.8.1.pom 06-8-4
9:46:49 AM: Downloaded [central] -> http://repo1.maven.org/maven2/junit/junit/3.8.1/junit-3.8.1.pom
06-8-4 9:46:51 AM: Downloading [central] -> http://repo1.maven.org/maven2/junit/junit/3.8.1/junit-3.8.1.jar
06-8- 4 9:47:00 AM: Downloaded [central] -> http://repo1.maven.org/maven2/junit/junit/3.8.1/junit-3.8.1.jar
-------- -------------------------------------------------- ------
Supplementary correction: If there is an error message and you also have a shelf package, you can use maven's instructions for localized installation. For example, when I installed the hibernate shelf package, it told me that jta could not be downloaded. If localized installation is required, the tips given are as follows:
1) javax.transaction:jta:jar:1.0.1B
Try downloading the file manually from: http://java.sun.com/products/jta.Then , install it using the command:
mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta \ -Dversion=1.0.1B -Dpackaging=jar -Dfile=/path/to/filePath to dependency:
1) com.efn:mywebapp:war:1.0-SNAPSHOT
2) org.hibernate:hibernate:jar:3.1rc2
3) javax.transaction:jta:jar:1.0.1B
----------
1 required artifact is missing.for artifact: com.efn:mywebapp-1.0-SNAPSHOT.war This prompt means that you can download the jta shelf package from the sun website first, and then install it as required by the command line, because I already have this shelf package, then copy it to a convenient location, such as c:\, and then enter at the command line:
mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile After the execution of =C:/jta.jar
, everything is OK!
------------------------------------ --------------------------


2. Manual configuration
        Manual configuration is more troublesome than automation, but everything is in your own hands There is always enough to eat and drink, no one will accept it, not J. And once you configure it, you can benefit from it for a lifetime. More importantly, it can solve tasks that cannot be done by automation. For example, if I want to configure oracle's jdbc driver now, if I use automation, it prompts me that I can't download it, so I can change the download address, etc. It's really tiring.
        Come on by yourself.
        Before manual configuration, let me introduce the relevant background knowledge. First of all, let's understand the concept of jar warehouse. Maven adopts a centralized way to manage shelf packages. All java projects built with maven can reuse the shelf packages under unified management. Therefore, there must be a place to store jar files in a unified manner. This is the jar warehouse. , a local repository will be created for both development and deployment. The default location of this repository is X:\Documents and Settings\Administrator.LIPENG\.m2\repository (X is the drive letter of your operating system). You can modify the configuration file to change the default output location. The configuration file is in the conf subdirectory of the maven directory. The file name is settings.xml. Add the following node information to the configuration file to D:/Repository. However, it is not recommended to change, it seems that the maven plugin of eclipse only recognizes the default output location. I just had a problem in this aspect and it took me a long time to find out that it was the problem of the output path, maybe I have
n't plug-in yet. If anyone solves this problem, don't forget to share it with everyone.
Now let's analyze the structure of the configuration file pom.xml, taking junit as an example, the format is as follows:


xml code
1.
<dependencies> 

2.
<dependency> 

3.
<groupId>junit</groupId> 

4.
<artifactId>junit</ artifactId> 

5.
<version>3.8.1</version> 

6.
</dependency> 


</dependencies>  Let's


take a look at the local warehouse directory structure
Repository
`-- junit
|-- junit
| `-- 3.8.1
| `-- junit-3.8.1.jar
Now everyone should understand it, let's not say redundant words La. Draw a scoop according to the gourd. But pay attention to building the directory first and then writing the configuration file, otherwise, the smart plug-in will start to download immediately once it is saved...


Now start to manually create the oracle jdbc directory and configure the file, first create the directory structure as follows:
Repository
`-- ojdbc
|-- ojdbc
| `-- 14
| `-- ojdbc-14.jar
If the jar file you have is named ojdbc14.jar, change it to ojdbc-14.jar, write the configuration file:


xml code
1.
<dependency> 

2.
<groupId >ojdbc</groupId> 

3.
<artifactId>ojdbc</artifactId> 

4.
<version>14</version> 

5.
</dependency> 


So now a full pom.



1.
<?xml version="1.0"?>

2.
<project> 

3.
<modelVersion>4.0.0</modelVersion> 

4.
<groupId>com.mycompany.app</groupId> 

5.
<artifactId>myapp</artifactId> 

6.
<name>Maven Quick Start Archetype</name> 

7.
<version>1.0-SNAPSHOT</version> 

8.
<url> http://maven.apache.org </url> 

9.
<dependencies> 

10.
<dependency> 

11.
<groupId>ojdbc</groupId> 

12.
<artifactId>ojdbc</artifactId> 

13.
<version>14</version> 

14.
</dependency> 

15.
<dependency> 

16.
<groupId>junit</groupId> 

17.
<artifactId>junit</artifactId> 

18.
<version>3.8.1</version> 

19.
</dependency> 

20.
</dependencies> 

21.
< /project> 



Save it, you will find that the project management perspective has changed a little. According to this method plus the jdbc frame package, you can now start writing programs. Create a class and add the main function. The program is written as follows:


java code
1 .
public static void main( String[] args )  

2.
{  

3.
Connection conn = null;  

4.
PreparedStatement ps = null;  

5.
ResultSet rs = null;  

6.
try {  

7.
Class.forName("oracle.jdbc.   driver.OracleDriver");  

8.
conn = DriverManager.getConnection("jdbc:oracle:thin:@(description=(address_list=(address=(protocol=TCP)(port=1521)(host=192.168.0.240)))(connect_data=(SERVER = DEDICATED)(SERVICE_NAME = db.efriendnet.com)))", "efnx", "efnx");  

9.
ps = conn.prepareStatement("select * From tb_partyinfo");  

10.
rs = ps.executeQuery();  

11.
while(rs.next())  

12.
{  

13.
System.out.println(rs.getString("topic"));  

14.
}  

15.
} catch (Exception e) {  

16.
System.out.print(e.getMessage());  

17.
}  

18.
finally 

19.
{  

20.
if (rs != null) {try {rs.close();} catch (SQLException e) {}}  

21.
if (ps != null) {try {ps.close();} catch (SQLException e ) {}}  

22.
if (conn != null) {try {conn.close();} catch (SQLException e) {}}  

23.
}  

24.




Don't forget to import the corresponding package


8. compiler
uses maven Build system, the compilation process is independent. At this time, if you use the compiler tool that comes with eclipse, it will not work. So to compile, debug, and run some work. In the past, it was compiled in the dos command line mode. Now the plug-in is very easy to use, and it can be compiled after configuring it in eclipse. very convenient. Now for an introduction.


Eclipse has an extension tool that is used to integrate other build tools. Right-click on the node of the project, select Properties, select the "New" button in the right window of "Compile", and enter in the "name" of the dialog box: study, Click "Browse Workspace..." to list the projects for selection.
After selecting, enter package in goals. Don't forget to apply. Well, let's Run. If everything is normal, the
console will print the maven compilation information as follows:
[INFO] ---------------------------------------------------------------------
[INFO] Building Maven Quick Start Archetype
[INFO] task-segment: [package]
[INFO] ---------------------------------------------------------------------
[INFO] resources:resources
[INFO] Using default encoding to copy filtered resources.
[INFO] compiler:compile
[INFO] Nothing to compile - all classes are up to date
[INFO] resources:testResources
[INFO] Using default encoding to copy filtered resources.
[INFO] compiler:testCompile
[INFO] Nothing to compile - all classes are up to date
[INFO] surefire:test
[INFO] Surefire report directory: D:\eclipse\workspace\study\target\s
urefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.efn.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.157 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] jar:jar
[INFO] Building jar: D:\eclipse\workspace\study\target\study-1.0-SNAPSHOT.jar
[INFO] ----------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ---------------------------------------------------------------------
[INFO] Total time: 4 second
[INFO] Finished at: Fri Aug 04 10:55:42 CST 2006
[INFO] Memory 2M/7M
[INFO] ---------------------------------------- ----------------------------
Note, don't forget to go through this step of compilation after every program change. Because this is maven's compiler!


9. Debugging the program
After the above steps, we have completed the software life cycle under the management of mave, but as a program developer, we still need to debug. The debugging settings here are the same as the debugging of ordinary java programs.
First, open the debug dialog:
        because it is a general java application, we select Java Application, click the "New" button, enter some corresponding parameters, apply-Debug
Ok, everything is normal! Hope you are doing well too!


Ten, concluding remarks
This article is just a simple guide to the operation steps of maven, there are still many things to practice in practical application. If you find any mistakes and omissions, criticisms and corrections are welcome!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326551547&siteId=291194637