How to auto increment build number in project version?

I would like to have a build number which is auto incremented each time compileJava is run. That build number should be part of project.version. e.g.

allprojects {
version = “1.2.3.${buildNumber}”
}

What is the best way of doing this?

I’ve seen a number of posts for auto increment build number for gradle but they all are for Android or iOS and do not involve changes to project.version, but instead use a separate variable.

I tried writing my own custom plugin which reads a build number from a java properties file and auto increments it. The plugin works, but when I set project.version = “1.2.3.${buildinfo.buildNumber}” the buildinfo.buildNumber is null. It seems like project.version = “…” is evaluated before any external properties are available. See this post for more info: https://discuss.gradle.org/t/how-to-use-custom-plugin-to-set-version/13995