SAGARFIVE

Interview Questions

Maven Interview Questions

I. Maven Fundamental Level Interview Questions

  • Maven is a open-source project management build/build automation tool developed by Apache Software Foundation
  • It packages the source code and makes an artifact (Machine understandable code package).
  • Primarily used for java projects
  • Maven can also be used to build and manage projects written in C#, Ruby, Scala
  • Apache Maven is a software project management and comprehension tool.
  • Based on the concept of a project object model (POM)
  • Maven can manage a project’s build, reporting, and documentation from a central piece of information.

A build tool takes care of everything for building a process of application/software. Main aspects

(i) Generates source code (if auto-generated code is used),
(ii) Generates documentation from source code
(iii) Compiles source code,
(iv) Packages compiled code into JAR of ZIP file
(v) Install the packaged code in local repository, server repository, or central repository

Some of build tools: ANT, MAVEN(Java), MS Build(c++, .NET), Pybuild(python)

  • We Install maven on Linux, Windows Machines Mostly
  • To Manage and build the artifacts of the java projects.
  • We can install Maven on Any Machine which supports Java RunTime Enviroment

     
       Why Maven: 

  • With Maven We can manage Java Projects
  • We can build the artifact from source code
  • We can run tests (unit and integrations tests)
  • We can genereate documentation using maven 
  • We can deploy the artifact in local/remote repository using maven

Prerequisites for maven installation:

OSSupports all major
RAMNo minimum requirement
Storage/Disk spaceApproximately expect at least 500MB.
RunTime EnvironmentsMaven 3.9+ requires JDK 8 or above to execute.
Installation files(offline) or use internet to downloadJava SDK, Maven binary file
Windows/OS with usage privilegeAdministrator access/ROOT Privilege

    We can install maven on Windows by using following steps :

  1. We need to Download JAVA SDK 1.7+, and install it
  2. Add JAVA Environment, System Variable
  3. Download Maven Binary zip file, extract to secured directory
  4. Add Maven Environment, System Variable
  5. Verify the installations on cmd
  6. Java : run java –version and for maven mvn –version

 

Full/Deatailed Article : https://sagarfive.in/maven/installing-maven-on-windows/

  • Maven needs Java RunTime Environment
  • When ever we install maven on Prod, Dev, QA Servers we need to install specified versions of JAVA and Maven Based on Java Project developed
  • Example :
    • If a java project has developed based on Java JDK 8, then we should/better to install the specified java on Prod, Dev, QA Servers
    • Also have to use/install particular maven version used on Dev Enviroment too
  • Update the repository : sudo apt-get update -y
  • Download JAVA JDK : sudo apt-get  install open-djk -y
  • Install maven : sudo apt-get  install maven -y
  • Add Environment variables : run the commans on terminal with installation paths/directories
    • export JAVA_HOME=/usr/lib/jvm/default-java
    • export M2_HOME=/opt/maven
    • export MAVEN_HOME=/opt/maven
    • export PATH=${M2_HOME}/bin:${PATH}

It’s clever question, industry never uses latest Maven, Java versions on on Prod, Dev, QA Servers, so better to focus very much on this question

One Variant of use case for a project: 

Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-24T18:41:47Z)
Maven home: /opt/maven
Java version: 10.0.2, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: ISO-8859-1
OS name: "linux", version: "4.15.0-36-generic", arch: "amd64", family: "unix"

* If get question like, Why you used open-jdk instead of jdk, then aswer it developement team desicion, so we implemented.
* Might be dev team what to use open-jdk beacuase it is open-source,
* Most of the versions works properly, but might be dependecy specific issue/need with that version of jdk

By running the maven version command on terminal, we can find the version of maven, which is

mvn –version   (or) 
mvn -v

Terminal Responce : 
Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-24T18:41:47Z)
Maven home: /opt/maven
Java version: 10.0.2, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: ISO-8859-1
OS name: “linux”, version: “4.15.0-36-generic”, arch: “amd64”, family: “unix”

  • Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to
    • create jar file
    • create war file
    • compile code files
    • unit testing of code
    • create project documentation
    • create project reports
  • A plugin generally provides a set of goals, which can be executed using the following syntax −
  • mvn [plugin-name]:[goal-name]
    mvn compiler:compile
  • Plugins are specified in pom.xml using the plugins element.

    Maven Plugin Types :

     

  • Build plugins : They execute during the build process and should be configured in the <build/> element of pom.xml.Part of Build life cycle
  • Reporting plugins : They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.Part of Site life cycle

    For More Detailed Explanation Visit : https://sagarfive.in/maven/plugins/


It is a complete project management tool.

  • It makes the build process very easy(No need to write long scripts) compared to ANT(old build tool used before maven)
  • It has a remote maven repo which has all the dependencies in one place.
  • Can be used with other programming languages too, just not java(we can also use for Ruby).
  • It also support parallel build feature in multi core machine for large multi module projects
  • It provides a uniform build system. It has a standard directory structure which is followed.
  • It follows Convention over Configuration.
Maven Features : 
  • A huge, continuously growing repository of user libraries
  • The ability to set up projects easily, using best practices
  • Dependency management, featuring automatic updating
  • Backwards compatible with previous versions
  • Strong error and integrity reporting
  • Automatic parent versioning
  • Ensures consistent usage across all projects
  • It’s extensible, and you can easily write plug-ins using scripting languages or Java.

Maven Take care of these

  1. Project Management
  2. Project Generation
  3. Project Build at build life cycle
  4. Deploying artifact at local or remote repository
  5. Preparing Reports at site life cyclea
  6. Pom file : Plugins, Dependencie

 

Maven is a build tool along with project management, These are the similar build tools

  • Apache ANT : 
    • Apache Ant is a software tool for automating software build processes Developed by Apache Tomcat in early 2000
    • For java, c, c++ project build
  •  Gradle : 
    • Gradle is a build automation tool for multi-language software development.
    • It controls compilation and packaging to testing, deployment, and publishing.
    • Supported languages include Java (as well as Kotlin, Groovy, Scala), C/C++, and JavaScript.
  • Maven is a complete Project managent management tools also we simple calls it as a build tool. 
  • We can say it’s like a framework, but it is more than of it
  • Because it is focus on complete project management, build, deploy and report generation and testing
  • In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful.

 

  • Maven : 
    Apache developed Maven to handle building multiple projects together, including publishing project information(reports), facilitating team collaboration, deploying projects(local or remote repository), and Building artifacts JARS,Wars  
  • Maven written in java/developed using java programming language to manage the project build 
  • How does it works deals with two ways : 1. Archetecture, 2. Process of work style

  • Archetecture: 
  • Maven Work flow :
    • Maven is works based on the concept of a project object model controlled from the pom.xml declarative file
    • Workflow is mainly focuses on Life cycle rules, mostly build life cycle
    • Lifecycles are : Build, Site and Clean

    • Build Life cycle  : When we run the mvn install/mvn package commands on terminal it starts compiling, building, Uses Required dependencies management and plugins are mentioned pom.xml file, run the tests, generates the artifact and deploys to local/remote repository.
      Commands we can use:
      mvn compile
      mvn test
      mvn package
      mvn install
      mvn deploy

    • Site Life Cycle :  When we run the mvn site Documentation/Reports creation
      mvn site

    • Clean Life cycle : Once Project created artifact, if we want run a fresh build, we need to clean, this is best way to clean
      mvn clean
  • ANT is a Opensource build automation tool developed by apache in 2000
  • Apache developed ANT to replace the default build tool which is make on unix
  • ANT works si
  • Developed using Java, Runs on Java Runtime Environment
  • Apache Maven is also developed by apache, it is full open source build and project management tool
  • Mainly difference in both is ANT has no life cycle rules and ANT scripts are not reusable
  • Maven Dependecies: once dependency/plugin downloaded for a Project, We can reuse them for next projects
MAVENANT
1It is mainly a project management tool.
Included build, documentation, reporting
It is mainly a build tool.
2Maven plugins are reusable.ANT scripts are not reusable
3Maven has a life cycleANT has No life cycle
4Maven is declarative
everything you define in the pom.xml file.
Ant is procedural, you need to provide information about what to do and when to do through code.
You need to provide order.
5Maven has a convention to place source code, compiled code etc. So we don’t need to provide information about the project structure in the pom.xml file.Ant doesn’t have formal conventions, so we need to provide information of the project structure in the build.xml file.
  • Maven projects are templating toolkits.
  • When want to start a project, we have to start from scrath it takes alot of time it implement all dependecies, pluing, file structure … more
  • Using maven projects, we can download a pre generated project template similar to your project, that contains basic/pre required all dependecies, pluing, file structure, so it saves time for developer
  • Maven has wide range of Projects, we can say maven community adds new project on time to time
  • Now/At the time of june 2023, the project available on maven is about 3282
  • Specific in case of types java, java with spring boot …and so many variants available
  • We can get that list by running the command at cmd/terminal(maven installed pc)
    mvn archetype:generate
  • Once after running above command, if it your first maven download archetype(Predefined structured project for specific application with sample data, first 1 is for Blank multi project for spring Boot + Elm)
    Now Maven has 3282 archetypes

  • Archetype is a Maven project templating toolkit.
  • An archetype is defined as an original pattern or model from which all other things of the same kind are made.
  • The name fits as we are trying to provide a system that provides a consistent means of generating Maven projects.
  • Archetype will help authors create Maven project templates for users, and provides users with the means to generate parameterized versions of those project templates.
  • Using archetypes provides a great way to enable developers quickly in a way consistent with best practices employed by your project or organisation.
  • We can get that list by running the command at cmd/terminal(maven installed pc)
    mvn archetype:generate
  • Once after running above command, if it your first maven Project, Maven downloads archetypes to your local machines
    Maven has 3282 archetypes at mid of 2023
 
  • Run the command in cmd(i have installed on c drive , so I opened cmd as run as administrator)
  • mvn archetype:generate

  • The Above command list all the achetypes, we did not mention the archetype, so maven chooses default sample maven-archetype-quickstart archetype
  • Also we can specify the archetype directly in the command to fast forword the process
  • C:\MVN>mvn archetype:generate
    -DarchetypeArtifactId = maven-archetype-quickstart 
  • We can some more information related to project like this
  • C:\MVN>mvn archetype:generate
    -DgroupId = com.companyname.bank 
    -DartifactId = consumerBanking 
    -DarchetypeArtifactId = maven-archetype-quickstart 
 
  • Run the command in cmd to create maven project in your pc 
    (i have installed on c drive , so I opened cmd as run as administrator)
  • mvn archetype:generate

      We can work offline in maven, but we need to follow some step

  1. Downloading all dependencies/plugins required to offiline/local:
    mvn dependency:go-offline
  2. Running maven in offline mode(which runs Maven goals and phases in offline mode)
    mvn -o verify
    This command will successfully execute all tests if we already downloaded all the required artifacts. Otherwise, it will fail.
    or
  3. Settings globally offline : It’s also possible to configure the offline mode globally by setting the offline property in the ~/.m2/settings.xml file:
    <settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0
    https://maven.apache.org/xsd/settings-1.0.0.xsd”>
    <offline>true</offline>
    </settings>

  • mvn package
  • It take the compiled code and package it in its distributable format, such as a JAR,
  • If we run the mvn package, mvn runs package’s previous build life cycle steps like mvn compile, mvn test and next executes the mvn package

  • When the packaged JAR/WAR Stored ? 
  • By default, the “mvn package” command will create the package in the “target” directory of your project.
  • However, you can specify a different output directory using the “-Dmaven.build.directory=<directory>” option.

  • How do I skip tests while running the “mvn package” command in Maven?
    You can skip running tests while running the “mvn package” command by using the “-DskipTests” option.
    For example, “mvn package -DskipTests“.
  •  
  • How do I specify a different Maven installation while running the “mvn package” or “mvn install” command?
    You can specify a different Maven installation by using the “-Dmaven.home=<path>” option.
    For example, “mvn package -Dmaven.home=/usr/local/maven“.

 

  • Project Management of Java or c# or Ruby
  • Dependecy management
  • Plugin Management
  • Compiling source code
  • Building artifact
  • Running Tests
  • Installing the package
  • Generating reports

The structure of maven project once generated using archetype command(structure varies with the type/variant of archetype)

This is the common/sample project directory structure:

Archetecture: 

  • Maven archetecture contains core along with cli, api, utils .. more
  • Each of them has specific work to do and combination of all makes the work of the maven
  • Archetecture diagram : https://people.apache.org/~jvanzyl/maven-3.2.0/
  • When we run the maven build commands like mvn package, maven check the pom.xml file(declarative file)
  • Maven download dependencies/plugins mentioned in pom.xml using api’s
  • Once downloading the dependencies/plugin starts building the package using resources of machine with cli and generate artifact
  • When we runs the mvn install, it deploys the artifact to local/remote repository which is mentioned in settings.xml
  • Maven uses it resources, utils to generate reports
  • When ever we creating a project in maven, we need to follow some naming convension, which are very much helpfull for project developement
    • version name : When we run archetype, we get list of predeveloped projects, if we select any one, that also contains version, we can select any one
      —-
      These below are actual naming convension  of maven project
    • groupid : org name (ex: com.oracleitech or choose any)
    • artifactid : project name ( reflected as a project folder name)
    • version : version what we developing (ex : v0.1)
    • package name : package name 
  • example of full naming conversion : com.oracleitech.maventestproject

    Full detailes process : https://sagarfive.in/maven/creating-simple-maven-project/
  • AWS CodeBuild is a fully managed aws services for continuous integration service that compiles source code, runs tests, and produces ready-to-deploy software packages.
  • In general, it a manage cloud service for maven 
  • We don’t need to install maven on any machine(So need to worry with infrastructure),
  • we can configure with project and run the builds using AWS Codebuild
  • More info : https://aws.amazon.com/codebuild/

II. Maven POM.xml Interview Questions

  • POM stands for Project Object Model.
  • It is a fundamental unit of work in Maven.
  • It is an XML file that resides in the base directory of the project as pom.xml.
  • The POM contains information in declarative way about the project and various configuration details used by Maven to build the project(s).
  • It stores all external API/Dependencies/Plugins information,
  • POM.xml Contains
    • Project
    • modelVersion
    • groupId
    • artifactId
    • version
    • Name & url
    • Properties
    • Dependencies
    • Build
    • plugins
  • Containes phases and goals in plugins
  • Structure:
<project>
  <modelVersion/>

  <parent/>

  <groupId/>
  <artifactId/>
  <version/>
  <packaging/>

  <properties/>

  <dependencyManagement/>
  <dependencies/>

  <build/>

  <reporting/>

  <profiles/>
</project>
  • Pom.xml is part of your maven project, using pom.xml, maven life cycle you can achieve it.
  • The pom.xml is a project object model which tells everything 3rd party tool dependencies and library’s and required plugins
  • it will give everything to your project like project means any java based web content like itself.
  • once you create the maven project you will get the pom.xml which is everything to handle your project
  • If you want to test your project, you need to add testing dependencies which is the maven community it will provide you once added it will have everything tested.

 

  • POM stands for Project Object Model.
  • It is a fundamental unit of work in Maven.
  • It is an XML file that resides in the base directory of the project as pom.xml.
  • The POM contains information in declarative way about the project and various configuration details used by Maven to build the project(s).
  • It stores all external API/Dependencies/Plugins information,
  • POM.xml Contains
    • Project
    • modelVersion
    • groupId
    • artifactId
    • version
    • Name & url
    • Properties
    • Dependencies
    • Build
    • plugins
  • By running any maven build life cycle command, maven checks the pom.xml, downloads the depedencies and plugins
  • And with mentioned declaration in pom.xml phases and goals are executed
  • POM.xml Contains
    • Project
    • modelVersion
    • groupId
    • artifactId
    • version
    • Name & url
    • Properties
    • Dependencies
      • dependency 1
      • dependency 2
    • Repositories
      • repository 1
      • repository 2
    • Build
      • plugins
      • goals

  • The execution tag is most commonly used to participate in some phases of the build lifecycle.
  • It execute the phase on basis of commands executed
  • Example : we can configure  maven-surefire-plugin to run in the testing phase of the build life cycle
  • Since surefire is bound to the test phase by default,
  • Example :
  •            <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M4</version>
                    <executions>
                        <execution>
                            <id>testngtest</id>
                            <phase>test</phase>
                        </execution>
                    </executions>
                    <configuration>
                        <suiteXmlFiles>
                            <suiteXmlFile>${testngxml.location}/testng.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin> 
  • This is the top-level element in all Maven pom.xml files.
  • This is the project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification.

 

<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/xsd/maven-4.0.0.xsd”>
  • This element indicates what version of the object model this POM is using.
  • The version of the model itself changes very infrequently but it is mandatory in order to ensure stability of use if and when the Maven developers deem it necessary to change the model.
  • It is the sub element of the project. It specifies the modelVersion. It should be set to 4.0.0.

 

  <modelVersion>4.0.0</modelVersion>

Groupid : 

  • groupid indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of a project
  • is typically based on the fully qualified domain name of your organization.
  • For example
    • The designated groupId for all Maven plugins is
    • org.apache.maven.plugins
  • Another example:
    • com.sagarfive


Artifactid: 

  • It is added to the project folder name
  • Indicates the unique base name of the primary artifact being generated by this project.
  • The primary artifact for a project is typically a JAR file.
  • Secondary artifacts like source bundles also use the artifactId as part of their final name.
  • A typical artifact produced by Maven would have the form <artifactId>-<version>.<extension>
  • For example
    • Myapp-1.0.jar
  • Another example:
    • Sample-app-v1.0.jar

Version : 

  • This element indicates the version of the artifact generated by the project.
  • Maven goes a long way to help you with version management and you will often see the SNAPSHOT designator in a version, which indicates that a project is in a state of development.
  • For example (Default value when generating maven project)
    • 1.0-SNAPSHOT
  • Another example:
    • v1.0

  • Name : This element indicates the display name used for the project. This is often used in Maven’s generated documentation.
  • url  : This element indicates where the project’s site can be found. This is often used in Maven’s generated documentation.

 

  • This element contains value placeholders accessible anywhere within a POM.
  • It stores the versions/values of specific items/terms/frames/dependecies/plugins

 

 <properties>   
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>   
         <maven.compiler.source>1.7</maven.compiler.source>   
         <maven.compiler.target>1.7</maven.compiler.target> 
</properties>

  • When we need a feature, we can develope from scratch or we can use open source feature as a dependent
  • if we use/depend on others or community developed feature we call them as dependecies
  • Example : Adding two API’s/Dependencies to your maven project,
              (i) SQL,
             (ii) Google static maps.
  • To get  dependency/API, Go to search.maven.com and search with name , select it with version and copy dependency code paste in pom.xml at the place of dependency section. And save it.
  • Dependencies are local, global and remote repositories
    For more info : https://sagarfive.in/maven/maven-repository-types/
  • build This element handles things like declaring your project’s directory structure and managing plugins.
  • Here we plugin information
<build>   
<pluginManagement>     
<plugins>       
<plugin>         
<artifactId>maven-clean-plugin</artifactId>         
<version>3.1.0</version>       
</plugin>     
</plugins>   
</pluginManagement> 
</build>
  • A Maven plugin is a group of goals; however, these goals aren’t necessarily all bound to the same phase.
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.pre-site</id>
                  <phase>pre-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>pre-site phase</echo>
                     </tasks>
                  </configuration>
  </plugin>
  • Maven is actually a plugin execution framework where every task is actually done by plugins. Maven Plugins are generally used to
  • create jar file
  • create war file
  • compile code files
  • unit testing of code
  • create project documentation
  • create project reports
  • A plugin generally provides a set of goals, which can be executed using the following syntax −
mvn [plugin-name]:[goal-name]
mvn compiler:compile

Maven Plugin Types :

1Build pluginsThey execute during the build process and should be configured in the <build/> element of pom.xml.Part of Build life cycle
2Reporting pluginsThey execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.Part of Site life cycle

More info : https://sagarfive.in/maven/plugins/

Example of plugin section in pom.xml : 

  • A Maven plugin is a group of goals; however, these goals aren’t necessarily all bound to the same phase.
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.pre-site</id>
                  <phase>pre-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>pre-site phase</echo>
                     </tasks>
                  </configuration>
  </plugin>
  • The super POM file defines all the default configurations. Hence, even the simplest form of a POM file will inherit all the configurations defined in the super POM file.
  • You we can view Super POM(Effective POM) using the command line (first you have to move in your project root folder where pom.xml file exist then type mvn help:effective-pom and press Enter as below

 

POM vs Super(effective) POM: 

  • Super pom contains all default values required for all projects
  • pom will get the default requied things from super pom
  • it is like parent and child relationship

 

  • child pom means actual direct pom.xml
  • Progation means similar starts exectution, so we can stop Progation by
  • Setting inherited tag to false prevents the propagation to child POMs.


Example : 

<plugins>
        <plugin>
            <!-- This declaration makes sure children get plugin in their lifecycle -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <!-- Configuration won't be propagated to children -->
            <inherited>false</inherited>
            <executions>
                <execution>
                    <!--This matches and thus overrides execution defined above -->
                    <id>checkstyle</id>
                    <!-- Unbind from lifecycle for this POM -->
                    <phase>none</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>

III. Maven Dependencies Interview Questions

  • When we need a feature, we can develope from scratch or we can use open source feature as a dependent
  • if we use/depend on others or community developed feature we call them as dependecies
  • these are similar to librarys 


Dependecies Types: 

  • Direct dependencies: These dependencies are explicitly included in a pom.xml file in the <dependencies> section.
    Read more : https://sagarfive.in/maven/dependencies-in-pom-xml/
  • Transitive dependencies: A project included as a dependency in a larger project can declare its own dependencies in a pom.xml file. These dependencies are then considered transitive dependencies to the primary project. When Maven pulls a direct dependency, it also pulls its transitive dependencies.
  • Dependencies with the scope system are always available and are not looked up in repository.
  • Means locally available dependencies within the system
  • They are usually used to tell Maven about dependencies which are provided by the JDK or the VM.
  • Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK,
  • but were available as separate downloads earlier. Typical examples are the JDBC standard extensions or the Java Authentication and Authorization Service (JAAS).
  • A simple example would be:

<project>

<dependencies>

<dependency>

<groupId>javax.sql</groupId>

<artifactId>jdbc-stdext</artifactId>

<version>2.0</version>

<scope>system</scope>

<systemPath>${java.home}/lib/rt.jar</systemPath>

</dependency>

</dependencies>

</project>

  • Maven dependencies stored at local repositorie
    1. Unix/Mac OS X – ~/.m2/repository
    2. Windows – C:\Users\{your-username}\.m2\repository

      By default, Maven local repository is defaulted to ${user.home}/.m2/repository folder :

  • When we compile a Maven project, Maven will download all the project’s dependency and plugin jars into the Maven local repository, save time for next compilation.
  • Finding local repository using command
    mvn help:evaluate -Dexpression=settings.localRepository
  • Change/Update local repository
    Find this file {MAVEN_HOME}\conf\settings.xml and update the localRepository

  • Sample settings.xml file

<settings>
<!– localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
–>

<localRepository>D:/maven_repo</localRepository>
</settings>

  • With dependencies, developer donot need to develop feature from scracth
  • Also we can use third party / open source tools integration to own projects
  • Maven can automatically add all the required dependencies by the dependencies we added to project build
  • If we want to stop adding any dependency, we use dependecy exclusion
  • Example pom.xml
    • <project>

      <dependencies>

      <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>1.1</version>
      <exclusions>
      <exclusion>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      </exclusion>
      </exclusions>
      </dependency>
      </dependencies>

      </project>
  • Maven can automatically add all the required dependencies by the dependencies we added to project build
  • If we want to stop adding any dependency, we use dependecy exclusion element
  • Example pom.xml
    • <project>

      <dependencies>

      <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>1.1</version>
      <exclusions>
      <exclusion>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      </exclusion>
      </exclusions>
      </dependency>
      </dependencies>

      </project>

Transitive dependencies: A project included as a dependency in a larger project can declare its own dependencies in a pom.xml file. These dependencies are then considered transitive dependencies to the primary project. When Maven pulls a direct dependency, it also pulls its transitive dependencies.

Dependency scope is used to limit the transitivity of a dependency and to determine when a dependency is included in a classpath.

There are 6 scopes:

  • compile
    This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
  • provided
    This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. A dependency with this scope is added to the classpath used for compilation and test, but not the runtime classpath. It is not transitive.
  • runtime
    This scope indicates that the dependency is not required for compilation, but is for execution. Maven includes a dependency with this scope in the runtime and test classpaths, but not the compile classpath.
  • test
    This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. This scope is not transitive. Typically this scope is used for test libraries such as JUnit and Mockito. It is also used for non-test libraries such as Apache Commons IO if those libraries are used in unit tests (src/test/java) but not in the model code (src/main/java).
  • system
    This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
  • import
    This scope is only supported on a dependency of type pom in the <dependencyManagement> section. It indicates the dependency is to be replaced with the effective list of dependencies in the specified POM’s <dependencyManagement> section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

    read more : link
  • Optional dependencies are used to decrease the transitive burden of some libraries.
  • These dependencies are used when it is not feasible to divide a project into sub-modules.
  • Some dependencies are only used for a specific feature in the project, and if that feature is not there, then that dependency will not be used.
  • It uses less storage : for every build we get an jar/war, so it keep on increasing used storage in local machine, if we store jar or war on remote, then we get free storage on local machine
  • it makes checking out project quicker, non need for versioning JAR files.
  • high availabiligy: if local machine went off, we can use jar/war/dependecies can used from remote
  • Maven external dependencies are described in the pom xml file just like other dependencies. The parameters required to define the external dependencies are groupidartifactId, scope set to system and system path as per the project location (relative path).
  • We can get external dependencies from : https://central.sonatype.com/
  • Example :
  • <dependency>
    <groupId>com.liferay</groupId>
    <artifactId>com.liferay.youtube.web</artifactId>
    <version>5.0.19</version>
    </dependency>
Maven PluginMaven Dependency
Plugins are software components that extend the functionality of another software application.Dependencies are external libraries or modules used to build and run a software project.
Handling Plugin is usually difficultManaging a dependency is comparatively easy.
Used to create jar files and compile code.Reproducible builds are created and maintained

IV. Maven Build Interview Questions

  • Build in maven is related to build in pom.xml and build life cycle
  • so Going with build in pom.xml
  • Build This element handles things like declaring your project’s directory structure and managing plugins.
  • plugins has phases and goals to execute some task
  • Here we plugin information
<build>   
<pluginManagement>     
<plugins>       
<plugin>         
<artifactId>maven-clean-plugin</artifactId>         
<version>3.1.0</version>       
</plugin>     
</plugins>   
</pluginManagement> 
</build>
  • build This element handles things like declaring your project’s directory structure and managing plugins.
  • Plugins contains phases and goals with that we clean the maven exisitng builds
  •  
  • pom.xml : clean life cycle
  • <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/xsd/maven-4.0.0.xsd”>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.companyname.projectgroup</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
    <build>
    <plugins>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.1</version>
    <executions>
    <execution>
    <id>id.pre-clean</id>
    <phase>pre-clean</phase>
    <goals>
    <goal>run</goal>
    </goals>
    <configuration>
    <tasks>
    <echo>pre-clean phase</echo>
    </tasks>
    </configuration>
    </execution>

    <execution>
    <id>id.clean</id>
    <phase>clean</phase>
    <goals>
    <goal>run</goal>
    </goals>
    <configuration>
    <tasks>
    <echo>clean phase</echo>
    </tasks>
    </configuration>
    </execution>

    <execution>
    <id>id.post-clean</id>
    <phase>post-clean</phase>
    <goals>
    <goal>run</goal>
    </goals>
    <configuration>
    <tasks>
    <echo>post-clean phase</echo>
    </tasks>
    </configuration>
    </execution>
    </executions>
    </plugin>
    </plugins>
    </build>
    </project>

Plugins are two types :

1

Build plugins

They execute during the build process and should be configured in the <build/> element of pom.xml.

2

Reporting plugins

They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.

V. Maven Build Profile Interview Questions

  • A Build profile is a set of configuration values, which can be used to set or override default values of Maven build.
  • Using a build profile, you can customize build for different environments such as Production v/s Development environments.
  • Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are triggered in variety of ways.
  • Profiles modify the POM at build time, and are used to give parameters different target environments (for example, the path of the database server in the development, testing, and production environments).

Types of Build Profile :

Build profiles are majorly of three types.

TypeWhere it is defined
Per ProjectDefined in the project POM file, pom.xml
Per UserDefined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)
GlobalDefined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)

For more : visit

  • Maven profiles can be used to create customized build configurations, like targeting a level of test granularity or a specific deployment environment.
  • With Profiles we can easily run the builds with multiple configurations instead spending time on modifying  or replication environment
  • We write properties in resource folder @ src/main/resources
    • env.properties
    • env.prod.properties
    • env.test.properties
  • Maven Build Profile
  • Specifiying the profile : Question 59
  • Activating/running build/test phase :  Question 60
  • The Maven build profiles are mentioned at pom.xml, User Settings.xml and Global Settings.xml
  • Example of specifiying the profile on settings.xml
    • <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.companyname.projectgroup</groupId>
      <artifactId>project</artifactId>
      <version>1.0</version>
      <profiles>
      <profile>
      <id>test</id>
      <build>
      <plugins>
      <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-antrun-plugin</artifactId>
      <version>1.1</version>
      <executions>
      <execution>
      <phase>test</phase>
      <goals>
      <goal>run</goal>
      </goals>
      <configuration>
      <tasks>
      <echo>Using env.test.properties</echo>
      <copy file="src/main/resources/env.test.properties"
      tofile="${project.build.outputDirectory}/env.properties"/>
      </tasks>
      </configuration>
      </execution>
      </executions>
      </plugin>
      </plugins>
      </build>
      </profile>
      </profiles>
      </project>

       

      **Run the maven test using test profile
      mvn test -Ptest

       
  • A Maven Build Profile can be activated in various ways.

    • Explicitly using command console input.
    • Through maven settings.
    • Based on environment variables (User/System variables).
    • OS Settings (for example, Windows family).
    • Present/missing files.
  • Examples :
  • Profile Activation via Maven Settings

    Open Maven settings.xml file available in %USER_HOME%/.m2 directory where %USER_HOME% represents the user home directory. If settings.xml file is not there, then create a new one.

      • <settings 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/xsd/settings-1.0.0.xsd”>
        <mirrors>
        <mirror>
        <id>maven.dev.snaponglobal.com</id>
        <name>Internal Artifactory Maven repository</name>
        <url>http://repo1.maven.org/maven2/</url>
        <mirrorOf>*</mirrorOf>
        </mirror>
        </mirrors>
        <activeProfiles>
        <activeProfile>test</activeProfile>
        </activeProfiles>
        </settings>

  • Explicit using command
    • mvn test -Ptest

Build profiles are majorly of three types.

TypeWhere it is defined
Per ProjectDefined in the project POM file, pom.xml
Per UserDefined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)
GlobalDefined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)

VI. Maven Plugin Interview Questions

  • Maven is actually a plugin execution framework where every task is actually done by plugins.
  • Maven Plugins are generally used to
    • create jar file
    • create war file
    • compile code files
    • unit testing of code
    • create project documentation
    • create project reports
  • A plugin generally provides a set of goals, which can be executed using the following syntax −
mvn [plugin-name]:[goal-name]
mvn compiler:compile
  • In addition to the plugins, we can also declare plugins in the pluginManagement section of the POM.
  • This contains the plugin elements in much the same way as we saw previously.
  • However, by adding the plugin in the pluginManagement section, it becomes available to this POM, and all inheriting child POMs.
  • any child POMs will inherit the plugin executions simply by referencing the plugin in their plugin section.
    • Sample pom.xml
      <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 https://maven.apache.org/xsd/maven-4.0.0.xsd”>

      <build>

      <pluginManagement>
      <plugins>
      <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.6</version>
      <executions>
      <execution>
      <id>pre-process-classes</id>
      <phase>compile</phase>
      <goals>
      <goal>jar</goal>
      </goals>
      <configuration>
      <classifier>pre-process</classifier>
      </configuration>
      </execution>
      </executions>
      </plugin>
      </plugins>
      </pluginManagement>

      </build>
      </project>
  • So maven-jar-plugin is mentioned under pluginManagement, so all the child pom files can access this maven-jar-plugin plugin
  • Maven Plugins are generally used to
    • create jar file
    • create war file
    • compile code files
    • unit testing of code
    • create project documentation
    • create project reports

Maven Plugin Types :

1Build pluginsThey execute during the build process and should be configured in the <build/> element of pom.xml.Part of Build life cycle
2Reporting pluginsThey execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.Part of Site life cycle


Some of plugins :

1cleanCleans up the target after the build. Deletes the target directory and artifact
2compilerCompiles Java source files.
3surefireRuns the JUnit unit tests. Creates the test reports.
4jarBuild artifact with jar format for the project
5warBuild artifact with war format for the project
6antrunRuns a set of ant tasks from any phase mentioned of the build.
7javadocGenerates Javadoc for the project.

More about : https://sagarfive.in/maven/plugins/

  • Maven offers a great variety of plugins to help us with the build of our project. However, we may find cases where these plugins are not enough and we have to develop our own.
  • Luckily, Maven provides some useful tools to help us in this process.
  • Full info : link

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files

Here’s the compiler plugin in the POM:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        ...
    </configuration>
</plugin>
Maven PluginMaven Dependency
Plugins are software components that extend the functionality of another software application.Dependencies are external libraries or modules used to build and run a software project.
Handling Plugin is usually difficultManaging a dependency is comparatively easy.
Used to create jar files and compile code.Reproducible builds are created and maintained

VII. Maven Setting.xml Interview Questions

Maven provides a settings file, settings.xml, which allows us to specify which local and remote repositories it will use. We can also use it to store settings that we don’t want in our source code, such as credentials.

In this tutorial, we’ll learn how to use the settings.xml. We’ll look at proxies, mirroring, and profiles. We’ll also discuss how to determine the current settings that apply to our project.

Configurations :

The settings.xml file configures a Maven installation. It’s similar to a pom.xml file but is defined globally or per user.

Let’s explore the elements we can configure in the settings.xml file. The main settings element of the settings.xml file can contain nine possible predefined child elements:

  • Plugin Groups
  • Proxies
  • Mirrors
  • Servers
  • Profiles
  • Properties
  • Plugin repositories
  • Active Profiles

More : https://sagarfive.in/maven/maven-settings-xml/

We can find the location : mvn help:effective-settings

The settings.xml file configures a Maven installation. It’s similar to a pom.xml file but is defined globally or per user.

Let’s explore the elements we can configure in the settings.xml file. The main settings element of the settings.xml file can contain nine possible predefined child elements:

  • Plugin Groups
  • Proxies
  • Mirrors
  • Servers
  • Profiles
  • Properties
  • Plugin repositories
  • Active Profiles
<settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
      xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd”>
    <localRepository/>
    <interactiveMode/>
    <offline/>
    <pluginGroups/>
    <servers/>
    <mirrors/>
    <proxies/>
    <profiles/>
    <activeProfiles/>
</settings>

Local Repository: 
Once we have installed Maven, by default, Maven’s local repository is configured to be ‘${user.home}/.m2/repository‘.

In different operating systems, these paths are resolved to –

  • Windows 7: C:/Documents and Settings/<username>/.m2/repository
  • Windows 10: C:/Users/<username>/.m2/repository
  • Linux: /home/<username>/.m2/repository
  • Mac: /Users/<username>/.m2/repository

Changing the local repository: 

  • Navigate to path {M2_HOME}\conf\ where M2_HOME is maven installation folder.
  • Open file settings.xml in edit mode in some text editor.
  • Find the tag <localRepository>
  • Update the desired path in value of this tag. Save the file.
    settings.xml
  • <settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd”>

    <!– localRepository
    | The path to the local repository maven will use to store artifacts.
    |
    | Default: ${user.home}/.m2/repository –>

    <localRepository>E:/devsetup/M2</localRepository>


    </settings>

 

Maven also allows us to override the location of the global and user settings via the command line:

$ mvn clean --settings c:\user\user-settings.xml --global-settings c:\user\global-settings.xml
  • Repositories can be declared inside a project pom.xml. This means that the developers sharing the project code get the right repository settings out of the box.
  • We can use mirrors in cases where we want to define an alternative mirror for a particular repository. This overrides what’s in the pom.xml.
  • For example, we can force Maven to use a single repository by mirroring all repository requests:

<settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd”>
<mirrors>
<mirror>
<id>aws-codeartifact-repository</id>
<name>AWS CodeArtifact Repo</name>
<url>https://aws.amazon.com/repo/maven2/</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
</settings>

  • The profiles element enables us to create multiple profile child elements differentiated by their ID child element.
  • The profile element in the settings.xml is a truncated version of the same element available in the pom.xml.
  • It can contain only four child elements:
    • activation,
    • repositories,
    • pluginRepositories, and
    • properties.
  • These elements configure the build system as a whole, instead of any particular project.
  • This is known as build project, changing the configurations on baisc of project and build

<settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd”>
    <profiles>
        <profile>
            <id>adobe-public</id>
            <repositories>
                <repository>
                    <id>adobe-public-releases</id>
                    <name>Adobe Public Repository</name>
                    <url>https://repo.adobe.com/nexus/content/groups/public</url>
                    <releases>
                        <enabled>true</enabled>
                        <updatePolicy>never</updatePolicy>
                    </releases>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </repository>
            </repositories>
        </profile>
       <profile>
            <id>adobe-public</id>
            <pluginRepositories>
               <pluginRepository>
                  <id>adobe-public-releases</id>
                  <name>Adobe Public Repository</name>
                  <url>https://repo.adobe.com/nexus/content/groups/public</url>
                  <releases>
                      <enabled>true</enabled>
                      <updatePolicy>never</updatePolicy>
                  </releases>
                  <snapshots>
                      <enabled>false</enabled>
                  </snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
        <profile>
            <id>baeldung-test</id>
            <properties>
                <user.project.folder>${user.home}/baeldung-tutorials</user.project.folder>
            </properties>
        </profile>
        <profile>
            <id>baeldung-test</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <jdk>1.8</jdk>
                <os>
                    <name>Windows 10</name>
                    <family>Windows</family>
                    <arch>amd64</arch>
                    <version>10.0</version>
                </os>
                <property>
                    <name>mavenVersion</name>
                    <value>3.0.7</value>
                </property>
                <file>
                    <exists>${basedir}/activation-file.properties</exists>
                    <missing>${basedir}/deactivation-file.properties</missing>
                </file>
            </activation>
        </profile>

    </profiles>
    <activeProfiles>
        <activeProfile>baeldung-test</activeProfile>
        <activeProfile>adobe-public</activeProfile>
    </activeProfiles>

</settings>

  • The pluginGroups element contains a list of child elements that specify a groupId. A groupId is the unique identifier of the organization that created a specific Maven artifact:
  • Maven searches the list of plugin groups when a plugin is used without a groupId provided at the command line. The list contains the groups org.apache.maven.plugins and org.codehaus.mojo by default.
  • The settings.xml file defined above allows us to execute truncated Tomcat plugin commands:
  • settings.xml:
    <settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd”>
    <pluginGroups>
    <pluginGroup>org.apache.tomcat.maven</pluginGroup>
    </pluginGroups>
    </settings>
  • Commands executing: 
    • mvn tomcat7:help
    • mvn tomcat7:deploy
    • mvn tomcat7:run

Servers : 

  • We add repositories in maven pom.xml, if it is private repository we need to add credentials like username, password and remote repository host url
  • Defining credentials in pom.xml is not secured, so instead of storing pom.xml, we store them on settings.xml with in server tag
  •  
  • pom.xml : 
    <repositories>
    <repository>
    <id>company.jfrog.io</id>
    <url>https://company.jfrog.io/company/release</url>
    </repository>
    </repositories>
  • Settings.xml :
    <settings>
    <servers>
    <server>
    <id>company.jfrog.io</id>
    <username>user-name</username>
    <password>user-password</password>
    </server>
    </servers>
    </settings>
Profiles : Question 73
  • SNAPSHOT is a special version that indicates a current development copy.
  • Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.
  • Now data-service team will release SNAPSHOT of its updated code every time to repository, say data-service: Release 1.1.53, replacing an older Release 1.1.52
  • A “snapshot” is a build which can be replaced by another build which has the same name. It implies that the build could change at any time and is still under active development.
  • enter image description here
  • pom.xml:
  • <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring</artifactId>
    <version>1.8-SNAPSHOT”</version>
    </dependency>
  • In case of Version, if Maven once downloaded the mentioned version, say data-service:1.0, it will never try to download a newer 1.0 available in repository.
  • To download the updated code, data-service version is need to be manually upgraded to 1.1.
  • In case of SNAPSHOT, Maven will automatically fetch the latest SNAPSHOT
  • (data-service:1.0-SNAPSHOT) every time app-ui team build their project.

Maven can have two settings files working at a time:

  • Maven installation directory: $M2_HOME/conf/settings.xml [Global settings file]
  • User’s home directory: ${user.home}/.m2/settings.xml [User settings file]


Both files are optional. If both files are present, the values in the user home settings file override the values from the global settings file.

  • Maven’s local repository is a directory on the local machine that stores all the project artifacts.
  • When we execute a Maven build, Maven automatically downloads all the dependency jars into the local repository. Usually, this directory is named .m2.

VIII. Maven Repository Interview Questions

Maven repository is a directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily. or
A maven repository is a directory of packaged JAR files with a pom.xml file. Maven searches for dependencies in the repositories.
Maven repositories are of three types

(i) Local Repository
(ii) Central Repository
(iii) Remote Repository

Maven repositories are of three types

  • (i) Local Repository
  • (ii) Central Repository
  • (iii) Remote Repository

(i) Local Repository :

  • Maven local repository is located in your local system.
  • It is created by the maven when you run any maven command.
  • It downloads the dependencies mentioned in pom.xml to local repository
  • By default, the maven local repository is %USER_HOME%/.m2 directory.
  • We can change the local repository location by editing maven settings.xml, by changing   <localRepository>

 

<settings xmlns = “http://maven.apache.org/SETTINGS/1.0.0”   xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance”   xsi:schemaLocation = “http://maven.apache.org/SETTINGS/1.0.0   http://maven.apache.org/xsd/settings-1.0.0.xsd”>   <localRepository>C:/MyLocalRepository</localRepository></settings>

(ii)  Central Repository :

  • Maven central repository is located on the web. It was created by the apache maven community itself.
  • The URL of the central repository is http://repo1.maven.org/maven2.
  • You can search the dependencies or API at webpage : https://central.sonatype.com/
  • Maintained by the Maven community.

(iii) Remote Repository :

  • Maven Remote Repository, which is developer’s own custom repository containing required libraries or other project jars.
  •  if we haven’t found any API/Dependencies. Maven remote repository is located on the web. Most of the libraries can be missing from the central repository such as JBoss library etc
  • so we need to define a remote repository in the pom.xml file. In the <dependencies> fields as <dependency>
  • Example :

 

<repositories>     
<repository>         
<id>companyname.lib1</id>         
<url>http://download.companyname.org/maven2/lib1</url>     
</repository> 
</repositories>
<!– https://mvnrepository.com/artifact/org.jboss.spec.javax.servlet/jboss-servlet-api_3.0_spec –><dependency>   
<groupId>org.jboss.spec.javax.servlet</groupId>   
<artifactId>jboss-servlet-api_3.0_spec</artifactId>   
<version>1.0.2.Final</version>   
<scope>provided</scope>
</dependency>

Local Repository :

  • Maven local repository is located in your local system.
  • It is created by the maven when you run any maven command.
  • It downloads the dependencies mentioned in pom.xml to local repository
  • By default, the maven local repository is %USER_HOME%/.m2 directory.
  • We can change the local repository location by editing maven settings.xml, by changing   <localRepository>

 

<settings xmlns = “http://maven.apache.org/SETTINGS/1.0.0”   xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance”   xsi:schemaLocation = “http://maven.apache.org/SETTINGS/1.0.0   http://maven.apache.org/xsd/settings-1.0.0.xsd”>   <localRepository>C:/MyLocalRepository</localRepository></settings>
  • By default, the maven local repository is %USER_HOME%/.m2 directory.
  • We can find the local repository in maven settings.xml(which global one)
  • Maven central repository is located on the web. It was created by the apache maven community itself.
  • The URL of the central repository is http://repo1.maven.org/maven2.
  • You can search the dependencies or API at webpage : https://central.sonatype.com/
  • Maintained by the Maven community.
  • Maven Remote Repository, which is developer’s own custom repository containing required libraries or other project jars.
  •  if we haven’t found any API/Dependencies. Maven remote repository is located on the web. Most of the libraries can be missing from the central repository such as JBoss library etc
  • so we need to define a remote repository in the pom.xml file. In the <dependencies> fields as <dependency>
  • Example :
<repositories>     
<repository>         
<id>companyname.lib1</id>         
<url>http://download.companyname.org/maven2/lib1</url>     
</repository> 
</repositories>
<!– https://mvnrepository.com/artifact/org.jboss.spec.javax.servlet/jboss-servlet-api_3.0_spec –><dependency>   
<groupId>org.jboss.spec.javax.servlet</groupId>   
<artifactId>jboss-servlet-api_3.0_spec</artifactId>   
<version>1.0.2.Final</version>   
<scope>provided</scope>
</dependency>

Maven Dependency Search Sequence :

When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence

1Local RepositorySearch dependency in local repository, if not found, move to step 2 else perform the further processing.
2Central repositorySearch dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to the local repository for future reference.
3Remote repositoryIf a remote repository has not been mentioned, Maven simply stops the processing and throws an error (Unable to find dependency).
Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference.Otherwise, Maven stops processing and throws error (Unable to find dependency).
  • Code Artifact is AWS Managed service for remote repository service
  • Here we can create private  maven central repository 
  • We can directly connect aws codeartifact repository to maven using auth token

IX . Maven Build Life Cycle Interview Questions

  • Maven is a build and project management tool
  • Life cycle is a complete workflow of maven from compiling, test to deploying the artifact
  • In Maven life cycle we have some stages
    • Maven build life cycle
    • Maven Clean life cycle
    • Maven site life cycle
  • Maven life cycle we have 3 stages
    • Maven build life cycle
    • Maven Clean life cycle
    • Maven site life cycl
  • About the stages:  

  • (i) Default or build Life cycle :  

    • This is used to build the application,
    • Phases Build Lifecycle : compile → test compile → test → package → integration-test → verify → install → deploy

    (ii) Clean Life cycle :

    • Maven clean is a plugin as the name suggests, that approaches to clean the files and directories generated by Maven at the time of its build.
    • The plugin removes the target folder that contains all the class files, docs, JAR files.
    • Phases of clean Lifecycle : pre-clean, clean, post-clean

    (iii) Site Life cycle :

    • This is used to generate the site documentation of the project.
    • Phases of a Site Life Cycle : pre-site, site, post-site, site-deploy

To add a local JAR file to a Maven project, you can use the maven-install-plugin. Here’s how you can do it:

  1. Place the JAR file in a directory that is accessible to your Maven project.

  2. Add the following build block to your pom.xml file:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-install-plugin</artifactId>
      <version>3.0.0-M1</version>
      <executions>
        <execution>
          <id>install-local-jar</id>
          <goals>
            <goal>install-file</goal>
          </goals>
          <configuration>
            <file>/path/to/local/jar/file.jar</file>
            <groupId>com.example</groupId>
            <artifactId>local-jar</artifactId>
            <version>1.0</version>
            <packaging>jar</packaging>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
  1. Replace /path/to/local/jar/file.jar with the path to your JAR file.

  2. Replace com.example with the desired group ID for the JAR file.

  3. Replace local-jar with the desired artifact ID for the JAR file.

  4. Replace 1.0 with the desired version for the JAR file.

  5. Run the following command to install the JAR file:

mvn install

This will install the JAR file to your local Maven repository, and you can then include it in your project by adding it as a dependency in your pom.xml file:

<dependencies>
  <dependency>
    <groupId>com.example</groupId>
    <artifactId>local-jar</artifactId>
    <version>1.0</version>
  </dependency>
</dependencies>
  • When we build a Maven project, it executes a set of clearly defined tasks based on the project pom.xml configuration and the command-line options.
  • This standard set of tasks creates the maven build lifecycle.
  • The benefit of a clearly defined lifestyle is that we have to remember only a few sets of commands to compile, build, install, and deploy our projects.
  • Maven build lifecycle goes through a set of stages, they are called build phases. For example, the default lifecycle is made up of the following phases

Mostly Used Default or Buid Phases/stages :

Sl.Stage/CommandInformation
1validateThis step validates if the project structure is correct. For example – It checks if all the dependencies have been downloaded and are available in the local repository.
2compileIt compiles the source code, converts the .java files to .class, and stores the classes in the target/classes folder.
3test-compileCompile the source code in the test destination directory
4testIt runs unit tests for the project.
5packageThis step packages the compiled code in a distributable format like JAR or WAR.
6integration-testIt runs the integration tests for the project.
7verifyThis step runs checks to verify that the project is valid and meets the quality standards.
8installThis step installs the packaged code to the local Maven repository.
9deployIt copies the packaged code to the remote repository for sharing it with other developers.
Mostly Used Default or Buid Phases/stages :
Sl.Stage/CommandInformation
1validateThis step validates if the project structure is correct. For example – It checks if all the dependencies have been downloaded and are available in the local repository.
2compileIt compiles the source code, converts the .java files to .class, and stores the classes in the target/classes folder.
3test-compileCompile the source code in the test destination directory
4testIt runs unit tests for the project.
5packageThis step packages the compiled code in a distributable format like JAR or WAR.
6integration-testIt runs the integration tests for the project.
7verifyThis step runs checks to verify that the project is valid and meets the quality standards.
8installThis step installs the packaged code to the local Maven repository.
9deployIt copies the packaged code to the remote repository for sharing it with other developers.
  • Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases
  • pre-site
  • site
  • post-site
  • site-deploy

Command : mvn site

PhaseDescription
pre-siteexecute processes needed prior to the actual project site generation
sitegenerate the project’s site documentation
post-siteexecute processes needed to finalize the site generation, and to prepare for site deployment
site-deploydeploy the generated site documentation to the specified web server
  • Maven clean is a plugin as the name suggests, that approaches to clean the files and directories generated by Maven at the time of its build.
  • The plugin removes the target folder that contains all the class files, docs, JAR files.
  • Phases of clean Lifecycle :
  • pre-clean,
  • clean,
  • Post-clean
  • Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus, when mvn clean command executes, Maven deletes the build directory.
  • We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.
  • In the following example, We’ll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases. This will allow us to echo text messages displaying the phases of the clean lifecycle.

 

PhaseDescription
pre-cleanexecute processes needed prior to the actual project cleaning
cleanremove all files generated by the previous build
post-cleanexecute processes needed to finalize the project cleaning
  • Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases
  • pre-site
  • site
  • post-site
  • site-deploy

 

PhaseDescription
pre-siteexecute processes needed prior to the actual project site generation
sitegenerate the project’s site documentation
post-siteexecute processes needed to finalize the site generation, and to prepare for site deployment
site-deploydeploy the generated site documentation to the specified web server

More :  https://sagarfive.in/maven/maven-site-lifecycle/

 

  • Maven is a build tool
  • To build an artifact we need to use maven build life cycle stages commands
  • The commands used to build artifact is
    • mvn package : package artifact in target folder
    • mvn install : copy artifact to local repository
  • When we run a phase, all goals bound to this phase are executed in order.
  • Here are some of the phases and default goals bound to them:
  • compiler:compile – the compile goal from the compiler plugin is bound to the compile phase
  • compiler:testCompile is bound to the test-compile phase
  • surefire:test is bound to the test phase
  • install:install is bound to the install phase
  • jar:jar and war:war is bound to the package phase
  • We can list all goals bound to a specific phase and their plugins using the command:

mvn help:describe -Dcmd=PHASENAME

  • For example, to list all goals bound to the compile phase, we can run:

mvn help:describe -Dcmd=compile

Example : build in pom.xml

<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven.failsafe.version}</version>
<executions> <execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>

</execution> </executions>
</plugin>
</plugins>
</build>

  • A Maven phase represents a stage in the Maven build lifecycle. Each
  • phase is responsible for a specific task.
  • Here are some of the most important phases in the default build lifecycle:
    • validate: check if all information necessary for the build is available
    • compile: compile the source code
    • test-compile: compile the test source code
    • test: run unit tests
    • package: package compiled source code into the distributable format (jar, war, …)
    • integration-test: process and deploy the package if needed to run
    • integration tests
    • install: install the package to a local repository
    • deploy: copy the package to the remote repository
      For the full list of each lifecycle’s phases, check out the Maven Reference.
      Maven phase command
  • mvn <PHASE>

Phase : 

Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

 

Goal : 

The task (action) that is executed. A plugin can have one or more goals.

One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

  • Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory.
  • Thus, when mvn clean command executes, Maven deletes the build directory.
  • We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.
  • In the following example, We’ll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases.
  • This will allow us to echo text messages displaying the phases of the clean lifecycle.

Phase Description

  • pre-clean execute processes needed prior to the actual project cleaning
  • clean remove all files generated by the previous build
  • post-clean execute processes needed to finalize the project cleaning

mvn package
This stage packages the compiled code in a distributable format like JAR or WAR

  • A Project Object Model or POM is the fundamental unit of work in Maven.
  • It is an XML file that contains information about the project and configuration details used by Maven to build the project.
  • It contains default values for most projects. Examples for this is the
    1. build directory, which is target;
    2. the source directory, which is src/main/java;
    3. the test source directory, which is src/test/java; and so on.
  • When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
  • When compile it’s finished, you should find the compiled .class files in the target/classes directory.
  • The package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory.
  •  jar: jar will not recompile sources;
  • it will imply just create a JAR from the target/classes directory considering that everything else has been done.
  • Mention the fully qualified artifact name of a project.

The order of inheritance in Maven(How maven strarts working) is:

  • Settings
  • CLI parameters
  • Parent POM
  • Project POM

In a real time project, a typical deployment process involves the below list of activities:

Manual Process : Each step we have to run the commands

  1. Checking in the code to the repository.
  2. Download the source code from the repository.
  3. Compile and build the application and generate jar/war from the same.
  4. Locate the generated war/jar in a common shared network location.
  5. Download the jar/war file and deploy to the target server
  6. Also, documentation and versioning details of the application needs to be update.


Auto deployment process using maven-release-plugin: 

  • Basically, to automate the build & release process in maven, release plugin of the maven will be used.
  • Open the pom.xml of the project and update as shown below:
    • <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”>
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.sample.webproject</groupId>
      <artifactId>SampleWebApp</artifactId>
      <packaging>war</packaging>
      <version>1.0 </version>
      <name>SampleWebApp Maven Webapp</name>
      <url>http://maven.apache.org</url>

      <scm>
      <url>http://www.svn.com</url>
      <connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/Framework</connection>
      <developerConnection>
      scm:svn:test/test123@localhost:8080:common_core_api:1101:code
      </developerConnection>
      </scm>

      <distributionManagement>
      <repository>
      <id>Sample-Web-App-Release</id>
      <name>Release repository</name>
      <url>
      http://localhost:8082/nexus/content/repositories/Sample-Web-App-Release
      </url>
      </repository>
      </distributionManagement>

      <build>
      <plugins>
      <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-release-plugin</artifactId>
      <version>2.0-beta-9</version>
      <configuration>
      <useReleaseProfile>false</useReleaseProfile>
      <goals>deploy</goals>
      <scmCommentPrefix>[Sample-Web-App-checkin]</scmCommentPrefix>
      </configuration>
      </plugin>
      </plugins>
      </build>

      <dependencies>
      <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
      </dependency>
      </dependencies>

      </project>

  • scmConfigures the scm (in this cases SVN is used) of the project
    repositoriesStorage location of the WAR/EAR/JAR file after the successful build
    pluginmaven-release-plugin to automate the process

Maven release plugin : 

  • mvn release:clean – cleans up the workspace for the last build and sets up for a fresh build.
  • mvn release:rollback – if the last process was unsuccessful, it reverts/rollback the workspace.
  • mvn release:prepare – This tasks performs the below list of operations:
    • Checks out for any uncommitted files in the local workspace.
    • Checks and ensures for no SNAPSHOT dependencies.
    • Prepares the Release version.
    • Updates the pom to SCM (SVN/Git/Mercurial/CVS)
    • Executes the test cases.
    • Performs the final commit to the SCM.
    • Tags the code.
    • Increments the version no. and adds the SNAPSHOT as part of the future releases.
  • mvn release:perform – checks out the code from the repository and runs the maven goal to build and deploy the artifacts to the repository.
  • Maven test is used to run unit test cases and integration test cases
  • Maven test has many commands
  • Maven has two different plugins related to tests.
  • maven-compiler-plugin, as its name suggests, handles compiling your code.
  • maven-surefire-plugin handles [unit] test execution and failing the build process if there are test failures
  • Maven-failsafe-plugin designed to run integration tests and as the name implies that when it fails, it does so in a safe way.
  • Failsafe and Surefire plugins are used to execute test cases in our maven based test automation frameworks.
  • We can also use JUnit (jJUnit unit 5) framework to run unit test cases
  • by adding dependency and configuring JUnit at maven-surefire-plugin to run unit tests

Maven has two test runs :

  1.  unit tests : using maven surefire plugin
  2. integration tests :  using failsafe plugin

 

  • The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application.
  • It generates reports in two different file formats Plain text files (.txt) XML files (.xml)
  • Maven surefire plugin is used to follow the sequence of tests in testng.xml file.
  • If we don’t include the Maven surefire plugin then it will execute all the testcases under src/test/java which has a prefix or suffix as ‘test’ and these tests will get executed without any sequence.
  • maven-surefire-plugin which is used by default whenever the test goal is executed [ with ‘mvn test’ / ‘mvn install’ or ‘mvn clean install’].
  • You can configure this plugin in pom.xml to provide some configuration information like the location of test artifacts [testng.xml] or option to include the conditions(defining group, excluding groups, thread-count, parallelism and skip directly with plugin configuration in pom.xml.
  • Thus you have the choice where to put that information(in pom.xml or in suite testng.xml)
  • All yours unit tests that have an annotation of @
  • test will be executed. But you can also use the plugin to add or exclude tests like such

Steps : 

  1. Adding JUnit to maven : Adding JUnit dependency in pom.xml
  2. Configuring the Maven Surefire Plugin in pom.xml:
  3. Writing a simple test case using JUnit framework:
  4. Running the test with maven : mvn test

More info : https://sagarfive.in/maven/maven-unit-testing-using-surefire-plugin/

  • The Failsafe Plugin is designed to run integration tests and as the name implies, when it fails, it does so in a safe way.
  • The Failsafe Plugin has only two goals:
    • failsafe:integration-test runs the integration tests of an application.
    • failsafe:verify verifies that the integration tests of an application passed.
  • The Maven lifecycle has four phases for running integration tests:
  • pre-integration-test for setting up the integration test environment.
  • integration-test for running the integration tests.
  • post-integration-test for tearing down the integration test environment.
  • verify for checking the results of the integration tests.
  • Command : mvn test or mvn clean test
  • The Failsafe Plugin generates reports in two different file formats:
    • Plain text files (*.txt)
    • XML files (*.xml)
  • By default, these files are generated in ${basedir}/target/failsafe-reports/TEST-*.xml.

For more : https://sagarfive.in/maven/maven-integration-testing-using-failsafe-plugin/

CommandInformation
1mvn testrun tests(unit and integration tests) using a suitable unit testing framework
These tests should not require the code be packaged or deployed
2mvn -Dtest=TestCircle testRunning a Single a class
3mvn -Dtest=TestCircle#mytest testRunning a specific method in a class
4mvn install -DskipTests or
mvn install -Dmaven.test.skip=true
Directly running install command(install the package in local repository)

Steps : 

  1. Adding JUnit to maven : Adding JUnit dependency in pom.xml
  2. Configuring the Maven Surefire Plugin in pom.xml:
  3. Writing a simple test case using JUnit framework:
  4. Running the test with maven : mvn test

More info : https://sagarfive.in/maven/maven-unit-testing-using-surefire-plugin/

X. Maven Advanced Interview Questions

  • Maven uses Convention over Configuration, which means developers are not required to create build process themselves.
  • Developers do not have to mention each and every configuration detail.
  • Maven provides sensible default behavior for projects. When a Maven project is created, Maven creates default project structure.
  • Developer is only required to place files accordingly and he/she need not to define any configuration in pom.xml.
  • As an example, following table shows the default values for project source code files, resource files and other configurations. Assuming, ${basedir} denotes the project location −
  • Item Default
    • source code ${basedir}/src/main/java
    • Resources ${basedir}/src/main/resources
    • Tests ${basedir}/src/test
    • Complied byte code ${basedir}/target
    • distributable JAR ${basedir}/target/classes
  • Maven uses convention instead of configuration, due to the fact that the developers only need to create a Maven project. The rest of the structure is automatically created.
  • There are many conventions present in Maven for setting up a project, building the artifacts, releasing the code, and running unit tests.

The order of inheritance in Maven is:

  • Settings
  • CLI parameters
  • Parent POM
  • Project POM

The default directory for the exploded WAR is
Project direcory/target/<finalName> .

  • An artifact is an output generated after a Maven project build.
  • It can be, for example, a jar, war, or any other executable file.
  • Also, Maven artifacts include five key elements,
    • groupId,
    • artifactId,
    • version,
    • packaging, and
      These information mentioned in pom.xml file

Those are the elements we use to identify the artifact and are known as Maven coordinates.

To produce execution debug output you could call Maven with X parameter or e parameter

For Maven <2.0.8, uncomment the following line in your %M2_HOME%/bin/mvn.bat (and maybe save the modified version as mvnDebug.bat):

@REM set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000

  • It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok.
  • To solve the issue, rename the id of one of the plugin

 

  • Profiles specified in the POM can modify the following POM elements:
    <repositories>
    <pluginRepositories>
    <dependencies>
    <plugins>
    <properties> (not actually available in the main POM, but used behind the scenes)
    <modules>
    <reports>
    <reporting>
  • Profiles specified in the POM can modify the following POM elements:
    <repositories>
    <pluginRepositories>
    <dependencies>
    <plugins>
    <properties> (not actually available in the main POM, but used behind the scenes)
    <modules>
    <reports>
    <reporting>
  • All POMs are inherited from a parent despite explicitly defined or not. This base POM is called Super POM and it contains values that are inherited by default.
  • So it inherit from the super pom(effective pom)
  • The above command is used to clear the project build file.
  • It will then copy any dependencies and execute all phases of the project.

We can force update in maven by using –U options by using mvn clean install command. In that –U means force update the dependencies of the snapshot. The release dependencies are updated is suppose there are not updated previously.

 

Commands :

mvn package -U
mvn install -U

  1. Eclipse is one of the most popular IDEs for Java and Android application development. It provides an excellent plugin, M2Eclipse, which integrates Maven and Eclipse.

  2. Go to the File option > In the drop-down menu, > select New
    Select the Project option
  3. Search for maven and select
  4. select archetype
  5. enter groupid, artifactid, verions
  6. Click next, Project creates and opens the project directory

A multi-module project is built from an aggregator POM that manages a group of submodules.

In most cases, the aggregator is located in the project’s root directory and must have packaging of type pom.

The submodules are regular Maven projects, and they can be built separately or through the aggregator POM.

 

More : link

  • if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency.
  • Adding external dependecy in pom.xml
    • <dependency>
      <groupId>ldapjdk</groupId>
      <artifactId>ldapjdk</artifactId>
      <scope>system</scope>
      <version>1.0</version>
      <systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath>
      </dependency>
      </dependencies>
  • Then we can run the commans like mvn install to build and deploy artifact

XI. Maven Experience based Interview Questions

It is your experince interms of years/months

It depends on your experience with maven
If your good enough say 7-7.5

The Maven Scripting Plugin is a plugin that wrapped the Scripting API according to JSR223. Add the scripting engines as dependencies of this plugin on its use.

Your ans : 

Common issues in Maven include:

  • Dependency conflicts.
  • Slow build times. : slow build overvcome by
      • Parallel Builds in Maven : cpu multicore
        mvn -T 4 install — will use 4 threads
        mvn -T 1C install — will use 1 thread per available CPU core
      • Running Maven Tests in Parallel
  • Plugin configuration problems. : to solve checking config files, modifying with right configs
  • Outdated repositories. : replacing with working repositories
  • Build and release only

  • to build and release mvn clean install

i have involved in this build phases

  • mvn test
  • mvn package
  • mvn clean
  • mvn install
  • mvn clean install

these are explain in above questions 

Integration maven with jenkins ,

running maven with jenkins using maven plugin with top level commands

to execute build life cycle and deployment of maven using jenkins

It is automated the workflow of building artifact and deploying to servers

=

No
But I just walk through the internet about alternatives of maven
ANT :  it is build tool, we have to develop from strach
Gradle : Gradle used to ruby, java, kotlin

No, 
But Now iam planning to learn python, i know a little bit shell scripting(if you know)

  1. Install git,maven, jenkins … in machine where you are working or config them if there are in different servers/remote
  2. Open jenkins and
  3. Configure maven plugin in jenkins
  4. Go to project > build > add maven  > add maven top level command
  5. mvn install
  6. This will creates jar/war package in local/remote repository based on configurations
  • If you are using jenkins for ci-cd of java project
  • then we need a run build to create a war/jar(Artifact)
  • So maven is a build tool, so we use

To skip running the tests for a particular project, set the skipTests property to true. You can also skip the tests via the command line by executing the following command:

mvn install -DskipTests

  • mvn package: builds an artifact in format of war/jar and keeps in /projectdirectory/target folder
  • mvn install : will copy/deploy the created artifact such as jar/war to local repository or remote repository

Doxia is used extensively by Maven and it powers the entire documentation system of Maven. It gives Maven the ability to take any document that Doxia supports and output it any format. The current version of Doxia base framework is 1.12.

  • The Maven Wagon Plugin, as the name implies, allows you to use various functions of a Maven wagon.
  • It allows you to upload resources from your build to a remote location using wagon. It allows you to download resources from a repository using wagon.
  • It allows to list the content of a repository using wagon.
  • This plugin is used to release a project with Maven, saving a lot of repetitive, manual work. Releasing a project is made in two steps: prepare and perform.
  • Phases are: 
  • release:clean Clean up after a release preparation.
  • release:prepare Prepare for a release in SCM.
  • release:prepare-with-pom Prepare for a release in SCM, and generate
  • release POMs that record the fully resolved projects used.
  • release:rollback Rollback a previous release.
  • release:perform Perform a release from SCM.
  • release:stage Perform a release from SCM into a staging folder/repository.
  • release:branch Create a branch of the current project with all versions updated.
  • release:update-versions Update the versions in the POM(s).

By enabling parallel execution, the JUnit engine starts using the ForkJoin thread pool.
Next, we need to add a configuration to utilize this thread pool. We need to choose a parallelization strategy.

JUnit provides two implementations (dynamic and fixed) and a custom option to create our implementation.

for more info :  link

mvn package – take the compiled code and package it in its distributable format, such as a JAR,
mvn install – install the package into the local repository, for use as a dependency in other projects locally

mvn clean install — clean the previous build information, and rebuild for new artifact

  • The location of your local repository can be changed in your user configuration. The default value is ${user. home}/. m2/repository/ 
  • in the repository we will have target folder, in the target folder artifact will save, when we run the mvn package
  • The SonarScanner for Maven is a Maven plugin that allows you to execute SonarCloud code analysis via a regular Maven goal.
  • As a Maven goal, the scanner is available anywhere Maven is available (locally, in CI services, etc.), without the need to manually download, set up, and maintain a separate installation.
  • It will check the code, bugs, code quality and code smells
  • it also has quality gates, if the source code not passed the quality gates then build process aborted
  • and mail will sent to developer and devops engineer


  • Nexus by Sonatype is a repository manager that organizes, stores and distributes artifacts needed for development.
  • It helps us to make and use private dependecy server, instead of using public repository as default
  • With this project/app won’t be affected, when public repository are failed to serve
  • and Own/Secured/Priavate dependencies/plugins uploading to public repositories are not good/secured, then we can config and use private repository like sonatype

How you upload aritfact to sonatype  :  link

  • Code Artifact is AWS Managed service for remote repository service
  • Here we can create private maven central repository
  • We can directly connect aws codeartifact repository to maven using auth token

Your ans _____

  1. config maven at local machine/cloud
  2. setup project
  3. setup settings.xml and pom.xml
  4. Create environment on aws
  5. create maven repository on codeartifact, add policy and add credentials aws credential /secretes manager
  6. update maven settings.xml and pom.xml with profile,server and build info with aws code artifact(we can see instructions, when we create code artifact repository on code artifact)’
  7. next run the maven commands, solve the issues if you face any
  8. check at codeartifact for artifact/dependencies

more : link