What is Mirror in Maven settings.xml file?

Correct me if I’m wrong, but a Mirror is used to redirect all traffic to a specific repository URL and block everything else (including Maven central repo).

This is not entirely correct. Artifacts are downloaded by Maven by searching them inside defined repositories. Those repositories are defined in project’s POM or in the Maven settings. But, as specified in the Mirror documentation:

However, you may want to use an alternative mirror for a particular repository without changing the project files.

Let’s take the example from the documentation and comment on it:

<mirrors>
  <mirror>
    <id>UK</id>
    <name>UK Central</name>
    <url>http://uk.maven.org/maven2</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

This defines a single mirror that will be used when Maven will want to fetch a dependency from the Maven Central Repository. Let’s say you have 2 current repositories, which are Maven Central and a custom repo A. What happens is the following:

  1. You are declaring a dependency to an artifact;
  2. Maven will look for that dependency inside your defined repositories, so it will look for it inside the repository A and Maven Central;
  3. Let’s say it starts with A: it will hit the URL defined for that repository, like you would expect. Then let’s say it wasn’t found there;
  4. It will then look inside Maven Central. However, Maven will notice that a mirror was configured for that repository. It will not hit Maven Central at repo1.maven.org. Instead, it will fetch it from uk.maven.org, which is the URL defined in the mirror configuration element.

As this example shows, a mirror only applies to certain repositories, which are defined with the <mirrorOf> configuration element. In the previous case, we had <mirrorOf>central</mirrorOf> which means “Mirror Maven Central”. This element can have various values, and the documentation gives examples:

Examples:

  • * = everything
  • external:* = everything not on the localhost and not file based.
  • repo,repo1 = repo or repo1
  • *,!repo1 = everything except repo1:

Now what if I have a Mirror to http://a.com:8081 and a repository to http://b.com:8081. Would the second URL ever get used? I assume the answer is a No.

The above shows that the answer is not strictly no. The mirror to http://a.com:8081 will be used when Maven will try to fetch a dependency from one of the repository that it mirrors. If it indeed mirrors the repository to http://b.com:8081 then no requests will ever be made to http://b.com:8081 (they will be redirected to http://a.com:8081); but if it doesn’t, Maven will continue to fetch dependencies from http://b.com:8081 like usual.


Can you have multiple Mirrors?

Yes, you can.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)