DEV Community

Micael Vianna
Micael Vianna

Posted on

How to automatically change your java SDK using sdkman

What

When managing multiple projects on your machine, you may need to manage multiple versions of java (or other SDKs), and changing this constantly can be a pain.

Using sdkman, we can manage this automatically.

Requirenments

sdkman :)

How

First of all, we need to enable the auto_env function, which will make the exchange happen whenever the directory is accessed via the terminal

To do this, edit the config file inside ~/.sdkman/etc/config and change the value for auto_env to true, or, use this command where $HOME is your home folder

sed -i 's/sdkman_auto_env=false/sdkman_auto_env=true/' "$HOME/.sdkman/etc/config"
Enter fullscreen mode Exit fullscreen mode

After this change, access your project folder, select the JDK (eg sdk use java 8.0.292-open) and run the command:

sdk env init
Enter fullscreen mode Exit fullscreen mode

This command will create a file called .sdkmanrc which contains the JDK definition for this project.

# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.292-open
Enter fullscreen mode Exit fullscreen mode

and

# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.10-zulu
Enter fullscreen mode Exit fullscreen mode

Result

After running this process, every time you access the folders you will notice the JDK change

$ cd my-project/
Using java version 17.0.10-zulu in this shell.
$ cd ../my-project-2
Using java version 8.0.292-open in this shell.
Enter fullscreen mode Exit fullscreen mode

Resources

Top comments (0)