Home  >  Maven

Maven Profile to Copy File

By Arvind Rai, May 29, 2021
Here we will create a Maven profiles to copy files. We will create two profiles, one for production environment and second for development environment. For the example, we have two log4j files in our resources directory.
The resources directory structure is as following.
src/main/resources
|
|--log4j.dev.properties
|
|--log4j.prod.properties 
Find the code snippet of Maven tasks for deleting and copying the file.
<tasks>
	<delete file="${project.build.outputDirectory}/log4j.properties" />
	<copy file="src/main/resources/log4j.dev.properties"
		tofile="${project.build.outputDirectory}/log4j.properties" />
</tasks> 
The delete task is to delete the specified file and copy task is to copy the file from a given source location to given destination location.



Creating Profiles for Dev and Prod Environment

We will create two Maven profiles, one for dev and second for prod here.
pom.xml
<project>
    ------ 
	<profiles>
		<profile>
			<id>dev</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-antrun-plugin</artifactId>
						<executions>
							<execution>
								<phase>package</phase>
								<goals>
									<goal>run</goal>
								</goals>
								<configuration>
									<tasks>
										<delete file="${project.build.outputDirectory}/log4j.properties" />
										<copy file="src/main/resources/log4j.dev.properties"
											tofile="${project.build.outputDirectory}/log4j.properties" />
									</tasks>
								</configuration>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>prod</id>
			<activation>
				<activeByDefault>false</activeByDefault>
			</activation>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-antrun-plugin</artifactId>
						<executions>
							<execution>
								<phase>package</phase>
								<goals>
									<goal>run</goal>
								</goals>
								<configuration>
									<tasks>
										<delete file="${project.build.outputDirectory}/log4j.properties" />
										<copy
											file="src/main/resources/log4j.prod.properties"
											tofile="${project.build.outputDirectory}/log4j.properties" />
									</tasks>
								</configuration>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>		
	</profiles>
</project> 

How to Run

Run Maven command as following.
mvn clean install 
The dev profile will run by default because activeByDefault value is true for this profile.
<activation>
	<activeByDefault>true</activeByDefault>
</activation> 
To run prod profile, use Maven command as following.
mvn clean install -Pprod 

References

Introduction to Build Profiles
Building For Different Environments
POSTED BY
ARVIND RAI
ARVIND RAI








©2021 concretepage.com | Privacy Policy | Contact Us