惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
WordPress大学
WordPress大学
小众软件
小众软件
Cloudbric
Cloudbric
AWS News Blog
AWS News Blog
腾讯CDC
量子位
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
Jina AI
Jina AI
Attack and Defense Labs
Attack and Defense Labs
S
SegmentFault 最新的问题
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
Google Online Security Blog
Google Online Security Blog
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
罗磊的独立博客
L
LINUX DO - 最新话题
博客园 - Franky
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
AI
AI
C
Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
I
Intezer
S
Securelist

Maciej Walkowiak - Java & Spring

Blog Generating HTTP clients in Spring Boot application from OpenAPI spec PostgreSQL and UUID as primary key Dynamic Projections with Spring Data JPA Container logs with Spring Boot and Testcontainers Reified Generics in Java? Faster integration tests with reusable Testcontainers and Flyway Running one-time jobs with Quartz and Spring Boot The best way to use Testcontainers with Spring Boot Spring Boot & Flyway - clear database between integration tests What's new in Spring? Activate Maven Profile by Operating System Spring Boot with Thymeleaf and Tailwind CSS - Complete Guide How to publish a Java library to Maven Central - Complete Guide Docker Compose - waiting until containers are ready Beautiful bash scripts with Gum Running Java on CRaC How to log PostgreSQL queries with Testcontainers Spring Boot 3.0 & GraalVM Native Image - not a free lunch Creating Spring Cloud Function projects with AWS SAM Loading classpath resources to String with a custom JUnit extension Creating Project Templates with Cookiecutter Auto-Registering JUnit 5 extensions Spring Boot component scanning without annotations Listing Maven dependencies in Spring Boot Actuator Info endpoint Spring Cloud AWS 2.3 RC2 Released How I built vlad-cli - command line interface to Vlad Mihalcea The State of Java Relational Persistence On Choosing a Tech Stack
Single file Java applications with JBang
2022-11-02 · via Maciej Walkowiak - Java & Spring
Published on
  • Java
  • Jbang
  • Spring Boot

Groovy has one feature I always wanted to have in Java - Grapes. Grapes let you define Maven dependencies inside the source code file and Groovy resolves them when you run the script. This enables writing applications that leverage whole ecosystem of Java libraries in a single-file.

groovy

@Grab('org.apache.httpcomponents:httpclient:4.2.1')
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet

def httpClient = new DefaultHttpClient()
def url = 'http://www.google.com/search?q=Groovy'
def httpGet = new HttpGet(url)

def httpResponse = httpClient.execute(httpGet)

new File('result.html').text =httpResponse.entity.content.text

While such thing cannot be done with pure Java, it can work with a help of JBang.

JBang ​

JBang - a CLI created by Max Rydahl Andersen (who happens to be also Quarkus co-lead) lets you run Java code with minimum setup. It handles resolving dependencies and even installing the JDK version you declare.

This is an equivalent of the Groovy script from above:

java

//usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 17
//DEPS org.apache.httpcomponents:httpclient:4.2.1

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientDemo {
    public static void main(String[] args) throws IOException {
        var httpClient = new DefaultHttpClient();
        var httpGet = new HttpGet("http://www.google.com/search?q=Groovy");

        var httpResponse = httpClient.execute(httpGet);

        try(var writer = new FileOutputStream("result.html")) {
            writer.write(httpResponse.getEntity().getContent().readAllBytes());
        }
    }
}

Which can be run with:

bash

$ jbang run HttpClientDemo.java

No Maven, no Gradle, no complex directory structure. Just one single command to use.

It makes Java feel almost like a scripting language, just better.

JBang with Spring Boot ​

Why not use this approach to develop a Spring Boot application? Lets try:

java

//usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 17
//DEPS org.springframework.boot:spring-boot-starter-web:2.7.5

package app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @GetMapping("/")
    String hello() {
        return "hello world";
    }
}

Executing:

bash

$ jbang run MyApp.java

starts a Spring Boot application on port 8080.

Building a JAR ​

JBang can also build an executable JAR file:

bash

$ jbang export portable MyApp.java

It will create a MyApp.jar file containing our source code, and all the dependencies will land in lib directory. At this stage, there is no option to build a single fat-jar containing both our code and the dependencies.

Building a Dockerimage for JBang application ​

To make it a bit more production ready, we can easily build a Docker image:

Dockerfile

FROM jbangdev/jbang-action AS build

RUN mkdir /app
WORKDIR /app
COPY . /app

RUN jbang export portable MyApp.java

FROM openjdk:17-alpine
RUN mkdir /app/
RUN mkdir /app/lib
COPY --from=build /app/MyApp.jar /app/MyApp.jar
COPY --from=build /app/lib/* /app/lib/
WORKDIR /app
CMD "java" "-jar" "MyApp.jar"

(please don't take it as an example of production ready Dockerfile - it's just for educational purposes 🙃)

Then build & run:

bash

docker build . -t my-app
docker run -p 8080:8080 my-app

IDE integration ​

I can't really write Java code without a proper IDE and autocompletion. The good thing is that there are JBang plugins for major IDEs:

Conclusion ​

I think JBang is a great addition to Java ecosystem. It is not a replacement for regular toolchain, but definitely enables experimenting with Java language and Java libraries by taking away all the heavy lifting related with setting up build files.

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed