Search code examples
javamavengradledependencies

Use separate dependency as per the platform


I have to include different dependencies according to the platform, for instance windows and linux using gradle/maven.

How can I make sure I only use the dependency needed for windows while building windows jar and linux while creating linux jar.


Solution

  • Maven pom.xml

    For Example,

    • SWT for Windows and Linux is different.
    • and when I use jpackage, On Windows, icon file is ico, On Linux, icon file is png
        <dependencies>
            <dependency>
                <groupId>${swt.groupId}</groupId>
                <artifactId>${swt.artifactId}</artifactId>
                <version>${swt.version}</version>
            </dependency>
    ...
    

    and Add profile

        <profiles>
    
            <profile>
                <id>linux</id>
                <activation>
                    <os>
                        <name>Linux</name>
                        <arch>amd64</arch>
                    </os>
                </activation>
                <properties>
                    <swt.groupId>org.eclipse.platform</swt.groupId>
                    <swt.artifactId>org.eclipse.swt.gtk.linux.x86_64</swt.artifactId>
                    <swt.version>3.119.0</swt.version>
                    <zname>linux_x86_64</zname>
                    <iconType>png</iconType>
                    <zformat>tar.gz</zformat>
                </properties>
            </profile>
    
    
    <profile>
                <id>windows</id>
                <activation>
                    <os>
                        <name>Windows 10</name>
                        <arch>amd64</arch>
                    </os>
                </activation>
                <properties>
                    <swt.groupId>org.eclipse.platform</swt.groupId>
                    <swt.artifactId>org.eclipse.swt.win32.win32.x86_64</swt.artifactId>
                    <swt.version>3.119.0</swt.version>
                    <zname>windows_x86_64</zname>
                    <iconType>ico</iconType>
                    <zformat>zip</zformat>
                </properties>
            </profile>
    ...
    

    How to know your activation os name and arch value ?

    Run mvn help:system | grep "os\." on Linux

    get result:

    os.name=Linux os.version=5.13.0-40-generic os.arch=amd64
    

    Run mvn help:system | findstr "os\." on Windows

    get result:

    os.name=Windows 10 os.version=10.0 os.arch=amd64
    

    Mapping os name and os arch into profile -> activation -> os -> name and os -> arch, then config profile -> properties Set the corresponding value into swt.groupId,swt.artifactId,swt.version.

    When you run mvn clean package , maven will auto select profile activation by mapping to os.name and os.arch value.