When building and managing Java projects with Maven, you may need to access external resources, such as the central repository or other remote repositories, via a proxy server. If you are in a restricted network environment where Internet access is limited, properly configuring the proxy is essential. The following outlines the specific steps and configuration methods for using Maven with a proxy:
Step 1: Configure the Maven settings.xml file
Maven's proxy configuration is defined in the user's settings.xml file, typically located in the ${user.home}/.m2/ directory. If the settings.xml file is not present, you can copy a template from the conf folder within the Maven installation directory.
Step 2: Add proxy configuration
In the settings.xml file, add a <proxy> element inside the <proxies> tag. Below is a typical proxy configuration example:
xml<settings> ... <proxies> <proxy> <id>example-proxy</id> <active>true</active> <protocol>http</protocol> <host>proxy.example.com</host> <port>8080</port> <username>proxyuser</username> <password>somepassword</password> <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy> </proxies> ... </settings>
Parameter explanations:
<id>: The identifier for the proxy; this is merely a name that you can set as needed.<active>: Indicates whether this proxy configuration is active; set totrueto enable it.<protocol>: The protocol used by the proxy server, typicallyhttporhttps.<host>: The address of the proxy server.<port>: The port number of the proxy server.<username>and<password>: Provide your credentials here if the proxy server requires authentication.<nonProxyHosts>: Define hosts that bypass the proxy; supports wildcards.
Step 3: Test the configuration
After configuration, run a Maven command such as mvn clean install to verify that the proxy is correctly set up. If configured properly, Maven should access remote repositories through the proxy server.
Example
Suppose you are in a corporate internal network and need to access external Maven repositories via your company's proxy server. The proxy server address is proxy.company.com, port is 8080, and it requires username and password authentication. Follow the steps and example above to configure your settings.xml file, ensuring all external requests go through the proxy server.
By following these steps and configurations, you can use Maven to build and manage your Java projects in environments where Internet access requires a proxy.