Configuring Maven to use Java 7 on Mac OS X

Recently I switched to Java 7 and then ran into a couple of issues. I had a Mac with OS X Mountain Lion (10.8.2) and Maven 3.0.4 (Maven installed using “brew install maven”). Both Java 6 and Oracle Java 7 was installed on the system with the default JVM set to Java 7:
$ java -version

But Maven was picking up Java 6:
$ mvn -version

The JAVA_HOME environment variable was set in ~/.profile:

but it was not exported. It turned out that brew had created a ~/.bash_profile file and the bash shell (from the bash man page):

looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

To use the settings in ~/.profile I could had moved them to .~/bash_profile but I decided to keep them in ~/.profile and instead load it from ~/.bash_profile using:
source .profile

After fixing the shell initialization files Maven was picking up Java 7 as expected.

Now I tried to launch mvn from within eclipse but got “Fatal error compiling: invalid target release: 1.7″. Eclipse was started from a shortcut to Eclipse.app rather than a shell so the JAVA_HOME variable was not set. I googled and found a workaround in http://jira.codehaus.org/browse/MNG-4226. It turned out that Maven loads settings from /etc/mavenrc if that file exists. I didn’t have that file on my system so I created it with:
echo JAVA_HOME=/usr/libexec/java_home -v 1.7 | sudo tee -a /etc/mavenrc

Finally Maven was picking up Java 7 both when run from the shell and from eclipse.

If you’re are facing problems with finding JAVA_HOME you might also want to check this article on Stack Overflow: Where is JAVA_HOME on OSX Lion?.

4 Comments

  1. Nick

    Just “upgraded” to Mavericks. This was what I needed to get back to work. You, sir, rock.

  2. I just had the same issue. I didn’t have problems with the mavenrc, however I installed maven on top of Java 1.6 so when I bumped to 1.7 without a JAVA_HOME set maven was still looking at 1.6. Using JAVA_HOME got “maven -v” to point to 1.7

    I hadn’t thought to check mvn -v to find my issue.

    Thank You,
    Dan Sabin

  3. Palako

    Does it work just like that for you? I had to add backticks so that the command executes and sets the variable properly. My /etc/mavenrc looks like this:

    $ cat /etc/mavenrc
    JAVA_HOME=/usr/libexec/java_home -v 1.7

  4. Palako

    Ah, I see what’s going on, the site is converting backticks into an outlined boxed style.

Leave a Reply