今日已更新 344 条资讯 | 累计 37249 条内容
关于我们

标签:#springboot

找到 39 篇相关文章

AI 资讯

🌱 Spring Boot Learning Series — Episode 2 | Spring Core

Episode 2 | Spring Core | Understanding IoC, Dependency Injection & Beans In Episode 1, I covered the WHY behind Spring — tight coupling, and how Spring takes over creating and providing objects (IoC + DI) instead of classes creating their own dependencies. This episode picks up from there with the parts I hadn't covered yet: how Spring actually does that under the hood — Beans, the Spring Container, and Component Scanning. 🔑 Keywords → 🧠 Understand → 💡 Why? → 💻 Practice → 🎯 Interview Questions → 🛠️ Project 🔑 Keywords for This Episode IoC & Dependency Injection (quick recap) Spring Bean Spring Container / ApplicationContext Component Scanning 1️⃣ Quick Recap: IoC & Dependency Injection From Episode 1: instead of a class creating its own dependency — public class TicketService { private TicketRepository repository ; public TicketService () { repository = new TicketRepository (); } } — Spring creates the dependency and hands it to the class. That's Inversion of Control (IoC) . In code, this usually looks like a constructor parameter: public class TicketService { private final TicketRepository repository ; public TicketService ( TicketRepository repository ) { this . repository = repository ; } } TicketService no longer says "let me create a TicketRepository." It says "I need a TicketRepository" — and Spring supplies one. That act of supplying it is Dependency Injection (DI) . IoC = who's in control of creating/managing objects → Spring. DI = how a class actually receives what it needs → passed in, not self-created. That's the recap. Now — where do these objects Spring creates actually come from, and where do they live? 2️⃣ Spring Bean — what Spring actually manages When Spring creates and manages an object for you, that object is called a Bean . This is the vocabulary you'll see everywhere in Spring code and docs, so it's worth being precise about it. @Service public class TicketService { } The @Service annotation is a signal to Spring: "this class should be managed b

2026-08-29 原文 →
开发者

I Built a Small API Gateway With Real Production Problems — On Purpose

Most gateway tutorials stop at "here's how you route a request." That's the easy 20%. The hard part is what happens when a client hammers you with requests, a downstream service falls over mid-traffic, or you're staring at a 500 trying to figure out which of your four services actually caused it. I wanted to build something that hits those problems on purpose, so I put together spring-gateway-sample : a public gateway , an api-server that fans out to two downstream services, and a full observability stack sitting behind all of it. It's not a real product and never will be. But I tried to make it behave like one — including the annoying bits, like config tradeoffs and races that most demos just quietly ignore. Stack, for context: Spring Boot 4.1, Spring Cloud Gateway on WebFlux, Resilience4j, Redis, Postgres, Keycloak, Prometheus/Grafana/Tempo/Loki, and a small Vue 3 app for throwing traffic at it from a browser. The system, in one request Browser (Vue traffic simulator) │ Keycloak PKCE login + API key ▼ Gateway ── JWT + API-key auth, Redis rate limiting ──▶ routes to │ ▼ api-server ── WebClient delegation, circuit breakers, Caffeine cache ──▶ │ │ ▼ ▼ product-service pricing-service (JPA / Postgres) (JPA / Postgres) Every hop re-validates the JWT on its own — defense in depth, so the gateway isn't the single thing standing between the internet and the data. The gateway also checks an API key on top, because a JWT tells you who the user is, not which client application is calling on their behalf. You need that second identity if you want per-client rate limits or the ability to revoke one app's access without touching anyone else's. Two checks, one specific order Every request needs a Keycloak JWT and an API key, and the order they're checked in isn't an accident: Missing or expired JWT → 401 , before the API key is even looked at. Valid JWT, bad API key → 401 , but a different error code. Both valid, wrong role → 403 . Why bother with the ordering? Because "you're no

2026-08-28 原文 →
开发者

Building a Full Enterprise-Ready React + Spring Boot Auth Flow: An End-to-End Guide

Introduction Authentication is one of those things that looks simple in a tutorial and becomes surprisingly complex in production. Between token storage, CSRF protection, refresh flows, and protected routing, there are many places to get it wrong—and getting it wrong has real security consequences. In two earlier posts, I covered pieces of this puzzle: Enabling CSRF in a JWT-Based React + Spring Boot Application and Storing Personal Information in React: sessionStorage vs Context API . This post ties those threads together into a complete, end-to-end authentication flow you can adapt for enterprise applications. We'll walk through the full journey: login → token issuance → secure storage → protected routes → token refresh → logout. Architecture Overview Before the code, here's the high-level flow: ┌──────────────┐ ┌──────────────────┐ │ React │ │ Spring Boot │ │ Frontend │ │ Backend │ └──────┬───────┘ └────────┬─────────┘ │ 1. POST /login │ │─────────────────────────>│ │ │ validate credentials │ 2. JWT (httpOnly cookie)│ issue access + refresh │<─────────────────────────│ │ │ │ 3. GET /protected │ │ (+ CSRF token) │ │─────────────────────────>│ validate JWT + CSRF │ 4. Protected data │ │<─────────────────────────│ │ │ │ 5. POST /refresh │ │─────────────────────────>│ rotate tokens │ │ │ 6. POST /logout │ │─────────────────────────>│ invalidate session Key Design Decisions Decision Choice Rationale Token storage httpOnly cookies Not accessible to JavaScript → mitigates XSS token theft CSRF protection Double-submit / token pattern Required when using cookies Token type Short-lived access + refresh Limits exposure window State management Context API for auth status Centralized, lightweight Why httpOnly cookies over localStorage? As I discussed in the storage blog, localStorage is readable by any script on the page—making it vulnerable to XSS. httpOnly cookies trade that risk for the need to handle CSRF, which we address below. Step 1: Backend — Login and Token Issuance

2026-08-22 原文 →
AI 资讯

Academic social network developed to connect students through knowledge exchange.

SkillShare is an academic social network developed to connect students through knowledge exchange, informal tutoring, and collaboration among users with different skills. The project aims to facilitate collective learning through a modern, dynamic, and responsive web platform. The project was developed as a Course Completion Project (TCC) for the Technical Course in Information Technology at the Escola Técnica de Brasilia (ETB).

2026-08-20 原文 →
AI 资讯

Run Local LLMs with Ollama and Spring AI

In the previous parts, we connected Spring AI with cloud-based AI models. But there is one important question: What if you don't want to send your data to an external AI provider? What if you want to: Run an LLM on your own machine Develop AI applications without API costs Work without an internet connection Keep sensitive company data private Experiment with different open-source models Build AI features locally before moving them to production This is where Ollama becomes very useful. In this article, we will learn how to run a local LLM using Ollama and connect it with Spring AI . We will build a simple real-world AI Customer Support Assistant using Java, Spring Boot, Spring AI, and Ollama. What We Are Building Our application will look like this: User | | HTTP Request v +---------------------+ | Spring Boot API | +---------------------+ | v +-------------+ | Spring AI | | ChatClient | +-------------+ | v +--------+ | Ollama | +--------+ | v Local LLM (Llama/Qwen) | v AI Response | v User The important part is that the LLM is running locally . There is no need to send every prompt to OpenAI, Anthropic, or another cloud provider. 1. What Is Ollama? Ollama makes it easy to run open-source LLMs locally. Instead of calling a remote API like: Spring Boot | v OpenAI API | v Cloud LLM we can run: Spring Boot | v Spring AI | v Ollama | v Local LLM Ollama can run models such as: Llama Qwen Gemma Mistral DeepSeek and many other compatible models The exact models available change over time, so always check the Ollama model library before choosing one. 2. Why Run an LLM Locally? Imagine you are building an internal HR application. Employees may send questions such as: What is our maternity leave policy? or: What is the process for requesting annual leave? You may not want internal company information leaving your infrastructure. A local LLM can help: Employee | v Spring Boot | v RAG / Business Logic | v Ollama | v Local LLM This can provide a useful privacy boundary. However

2026-08-20 原文 →
AI 资讯

From MySQL to MongoDB in Spring Boot — Everything That Changed in My Code

In my last post I wrote about an error that cost me a full evening: my pom.xml had the MongoDB starter, but my code was still full of JPA annotations. The compiler kept saying cannot find symbol: class Entity . That post was about the error. This post is about the fix — every single line I had to change to move my Task Manager project from MySQL to MongoDB. If you are planning the same switch, this is the checklist I wish I had. 1. The dependency Before (MySQL + JPA): <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-data-jpa </artifactId> </dependency> <dependency> <groupId> com.mysql </groupId> <artifactId> mysql-connector-j </artifactId> <scope> runtime </scope> </dependency> After (MongoDB): <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-data-mongodb </artifactId> </dependency> One starter replaces two dependencies. And this is exactly where my problem started — I added the new one but never removed the old one, so half my code still compiled and half did not. Remove the JPA starter completely. If you leave it in, the jakarta.persistence annotations still resolve, and you will not notice you are mixing two worlds until something breaks at runtime. 2. application.properties Before: spring.datasource.url = jdbc:mysql://localhost:3306/taskmanager spring.datasource.username = root spring.datasource.password = yourpassword spring.jpa.hibernate.ddl-auto = update spring.jpa.show-sql = true After: spring.data.mongodb.uri = mongodb://localhost:27017/taskmanager Five lines became one. No ddl-auto because MongoDB has no schema to create. No dialect because there is no SQL being generated. The database and the collection are created automatically the first time you insert a document. 3. The model class This is where most of the work was. Here is my actual Task class after the migration: package com.taskmanager.task_manager ; import com.fasterxml.jackson.annotation.JsonIgnore ; import org.

2026-08-19 原文 →
AI 资讯

The Outbox Pattern Is Not Enough

The textbook version of the transactional outbox is tight. You save the domain entity and an outbox row in one local transaction. A background scheduler picks up PENDING rows and publishes them to Kafka. You never publish inside the request thread — no dual-write, no atomicity breach. The pattern closes the consistency gap. Then you load-test it. I ran 1,000 authenticated requests through my event-driven platform in 70 seconds. The gateway returned 201 for every one of them. The outbox absorbed every row. The consumer drained everything. By every visible metric the system looked healthy. Underneath that health, I found three production-grade problems the textbook never mentioned. What a correct implementation looks like Before the problems, the shape of the solution. The outbox publisher runs on a @Scheduled virtual-thread worker: @Scheduled ( fixedDelay = 5000 ) @Transactional public void publishPendingEvents () { List < OutboxEvent > batch = outboxRepository . findTop20ByStatusOrderByCreatedAtAsc ( OutboxStatus . PENDING ); for ( OutboxEvent event : batch ) { event . setStatus ( OutboxStatus . PROCESSING ); outboxRepository . save ( event ); try { kafkaTemplate . send ( event . getTopic (), event . getPayload ()). get (); event . setStatus ( OutboxStatus . PUBLISHED ); } catch ( Exception e ) { event . incrementRetryCount (); if ( event . getRetryCount () >= MAX_RETRIES ) { event . setStatus ( OutboxStatus . FAILED ); } else { event . setStatus ( OutboxStatus . PENDING ); } } outboxRepository . save ( event ); } } This is correct. The PROCESSING state prevents another scheduler instance from claiming the same row. The retry cap prevents infinite cycling. The PENDING fallback on transient errors gives the event another chance. The dual-write problem is genuinely closed. Here is what that correctness does not cover. Gap 1: Your throughput ceiling is a config line fixedDelay = 5000 means the scheduler runs every 5 seconds. findTop20 means it picks up 20 rows per cycl

2026-08-18 原文 →
AI 资讯

Should your daily batch job live inside your main application?

Most Spring Boot services end up with a scheduled job in them somewhere. A nightly reconciliation, a report, an export to some partner system. It starts small, and it goes in the main app because that's where the domain code already is. One artifact, one deployment, one pipeline. That's a real advantage and it's why most teams do it. This post is about when that stops being a good trade, how to split the job out, and when you shouldn't. The memory problem Look at how much memory each workload uses over a day. The API is fairly flat. Warm heap, connection pool, some caches. It moves with traffic but it doesn't swing much. The batch job uses close to nothing for 23 hours, jumps while it runs, then drops back to nothing. When both live in the same JVM, the pod has to be sized for the peak. So every replica of your API holds batch-sized memory all day, for a job that runs once. With three replicas you're reserving that headroom three times over so one job can use it once, at 2am. Memory limits are not like CPU limits CPU is compressible. Go over your CPU limit and the kernel throttles you. The app gets slower and keeps running. Memory doesn't work that way. There's no "run with less" mode. If the container goes over its memory limit, the kernel kills the process. What you get is a container that exited with code 137 (that's 128 + 9, where 9 is SIGKILL). What you don't get is anything useful in the logs. No OutOfMemoryError , no stack trace, no heap dump unless you configured one and it had time to write, no shutdown hook. The JVM was running fine, asked for another page of memory, and got killed for it. So a batch job sharing a pod with your API is a way for a nightly job to take down the pods serving traffic. If the job's working set grows (bigger dataset, a table that keeps growing, one unusually heavy day) the thing that dies is the API. There's a quieter version of the same problem. Even when the job stays under the limit, it allocates heavily and triggers longer GC

2026-08-14 原文 →
AI 资讯

Axelix goes GA. A journey of a thousand miles begins with a single step

On behalf of the core Axelix team, and everybody who has contributed to the community, I want to declare: we finally did it. Axelix, finally, goes GA (Generally Available)! For those who do not know - Axelix is a product with an Open Source core, that allows you to discover the common problems, pitfalls and inefficiencies in Java applications at large scale. We're available on GitHub (btw - give us a star!). In this post, I want to share the story and the motivation behind the product overall. I hope you find it interesting. The Story. Big "Why" Behind Axelix Java is quite an interesting language and ecosystem in general. I think a lot of people will not argue that it is quite old, and it was one of the first so-called "Object-Oriented" languages, that actually gained massive adoption. It both was, and it still is the backbone of modern enterprise. For anyone who claims that Java is dead - I recommend checking the JetBrains State of Developer Ecosystem survey or even the Stack Overflow survey for 2025 (and Stack Overflow has, sadly, become a part of history). It is clear that Java as a language and the "ecosystem" around it (including Kotlin) is still relatively popular, and it remains true. Ecosystems around Languages The experienced developer knows that today's ecosystems that evolve around languages are typically very diverse. For example, let's talk about JavaScript. If we decide to run JavaScript on the server, then we're probably going to work with a database of some sort. Therefore, we're also going to need a framework, a library to work with the database, e.g. an ORM (I know that we may work without it but let's leave that aside). And in JavaScript, we have quite a lot of options: Prisma TypeORM DrizzleORM Kysely and so on. We can pretty safely state that Prisma ORM is probably the most used ORM on JavaScript . But notice that it is far from being the definitive JavaScript ORM. It is not like Prisma is the default choice and is by far the most popular ORM -

2026-08-11 原文 →
AI 资讯

Understanding Java's Virtual Threads: Lightweight Concurrency in Action

Understanding Java's Virtual Threads: Lightweight Concurrency in Action Java 21 introduced virtual threads as a stable feature (JEP 444), fundamentally changing how we approach concurrency on the JVM. In this post, we'll explore what virtual threads are, why they matter, and how to use them effectively. The Problem with Platform Threads Traditional Java threads—now called platform threads —are thin wrappers around operating system threads. Each one consumes roughly 1MB of stack memory and involves the OS scheduler for context switching. This makes them expensive: java // Creating thousands of platform threads is costly for (int i = 0; i < 10_000; i++) { new Thread(() -> { // blocking I/O ties up an OS thread processRequest(); }).start(); } In high-throughput server applications, the classic "thread-per-request" model hits a ceiling because you simply cannot create enough OS threads. Enter Virtual Threads Virtual threads are managed by the JVM rather than the OS. Many virtual threads run on a small pool of carrier platform threads. When a virtual thread blocks (e.g., on I/O), the JVM detaches it from its carrier, freeing that carrier to run other virtual threads. java // Creating a million virtual threads is perfectly fine try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0, 1_000_000).forEach(i -> { executor.submit(() -> { Thread.sleep(Duration.ofSeconds(1)); return i; }); }); } Key Benefits Cheap creation : Virtual threads start with a tiny stack that grows on demand. Familiar model : You write straightforward blocking code—no callbacks or reactive chains. Better scalability : Throughput is limited by resources, not thread count. Using Virtual Threads in Spring Boot As of Spring Boot 3.2, enabling virtual threads is a one-line configuration change: properties spring.threads.virtual.enabled=true This makes Tomcat handle each request on a virtual thread, allowing your application to serve many concurrent blocking requests without exha

2026-08-11 原文 →
AI 资讯

The Lombok Illusion (Chapter 5)

You open a new Spring Boot project and you create a DTO, then an entity, and you’re staring at getters, setters, constructors, equals() , hashCode() , toString() . Someone on the team suggests to put lombok’s @Data , or “just slap @Builder on it, it’ll be cleaner.” Forty lines become five and it looks great in the PR. Then it hits a real codebase, OpenAPI generation doesn't behave the way the build expects. Hibernate meets an auto-generated equals() and gets confused about identity. Something throws through a generated builder hierarchy at 2 AM, and the method you need to inspect doesn't exist in any file you can open. Eleven years into enterprise Java, my rule is simple: Lombok doesn't touch core application behavior. Not because writing a getter is interesting - it isn't, but because the handful of lines it saves rarely covers the compiler magic, tooling friction, and debugging problems it adds to something that has to survive for years after you've moved on to another project. "It just removes boilerplate" Worth asking what's actually being removed, though. A getter is part of your public API. A setter is a mutation point someone decided to expose. A constructor defines what states an object is allowed to enter. equals() and hashCode() define identity. toString() is what shows up in your logs when things go wrong at 3 AM. Write those by hand and they live in the source - visible, searchable, debuggable, owned by whoever's reading the file. Generate them with Lombok and the behavior is still there, it's just moved somewhere you can't see it without a separate step. The annotation most people reach for first time is @Data : @Data @Entity public class CustomerEntity { @Id @GeneratedValue private Long id ; private String email ; @OneToMany ( mappedBy = "customer" ) private List < OrderEntity > orders ; } One line and you get getters, setters, toString() , equals() , hashCode() across every field. For a JPA entity that's already a problem before you've written any bus

2026-08-10 原文 →
AI 资讯

Building a Production AI Agent in Spring Boot: A/B Testing Prompts With an LLM Judge (Part 9)

Last week I changed a system prompt based on a feeling. It was the first prompt change after the evaluation harness from Part 8 went live, and I was completely sure about it. The target was the markdown table. Part 8's first nightly run caught the agent answering price comparisons with a markdown table that renders broken in the chat frontend. The fix looked obvious: add one line to the system prompt demanding plain text. I checked six conversations by hand. All six looked better. I was ready to ship it to production. Then I ran the comparison the way Part 8 promised: the same 40 cases, the same judge, two prompts. The old prompt won. Not by a little. It won 18 pairs, lost 10, and tied 12, and the judge's rationales made the reason visible. The plain-text line had also made the agent terse, and terse answers dropped the order summary that customers actually need. My confidence was a sample size of one. The dataset was the jury. This part is about the pattern that settled that argument: pairwise comparison, the LLM-as-a-judge pattern for A/B testing prompts and tool descriptions before they reach production. It is the harness from Part 8, upgraded to answer "which version is better?" instead of "is this version good?" The Problem With Ship-by-Feeling Every prompt edit is an experiment with one sample. You notice one conversation where the agent is verbose, you add "be concise", and the change ships because that one conversation got better. The dataset from Part 8 makes the agent measurable, but a nightly score cannot tell you whether a change helped. One night is noise, three nights is a signal, and by the time you have three nights of data you have already shipped the change to every user. The variable itself is the problem. A system prompt and a tool description are the two things in an agent you cannot unit test. Part 6 proved the code is bug-free. Part 8 proved the answers are good on a fixed dataset. Neither says anything about whether your new wording is better

2026-08-10 原文 →
AI 资讯

Who Did This? Identity Across Async Boundaries

You put a lot of work into authentication. A gateway validates the Keycloak JWT, maps realm roles to authorities, checks that the caller is allowed. By the time a request reaches your service, you know exactly who is calling. Then the request crosses into async land, and all of that evaporates. This is the story of the point where identity quietly disappears in an event-driven system, why the dead-letter queue is the worst possible place for it to disappear, and how I made the acting user as durable and replay-safe as the event itself. The flow everyone believes is fine The platform is a set of Spring Boot services: an API gateway in front, a user-service on MySQL, a notification-service on PostgreSQL, and Kafka carrying events between them. A user is created, an event is published, a notification is sent. Authentication is handled at the edge. The gateway is an OAuth2 Resource Server; it validates the token once and propagates the caller's identity downstream as headers: // api-gateway — IdentityPropagationFilter (@Order(2), after security) IdentityContext identity = identityContextExtractor . extract ( jwt ); // Always set all three headers (empty when absent) to mask any spoofed values. enrichedRequest . putHeader ( IdentityHeaders . USER_NAME , nullToEmpty ( identity . username ())); enrichedRequest . putHeader ( IdentityHeaders . USER_EMAIL , nullToEmpty ( identity . email ())); enrichedRequest . putHeader ( IdentityHeaders . USER_ROLES , identity . rolesAsString ( DELIM )); One detail here matters more than it looks. The headers are always overwritten , even when a claim is absent. If a client tries to inject X-User-Name: admin on the inbound request, the gateway stomps it with the validated value (or empty). Downstream trust in those headers is only safe because the perimeter guarantees they cannot be forged. Miss that, and you've built an impersonation API. So far, so good. The synchronous hop carries identity. The problem starts one line later. The hidden f

2026-08-10 原文 →
AI 资讯

Your Service Map Is Lying

You attach the OpenTelemetry Java agent, point it at a collector, and within minutes Grafana is drawing a service map you never drew. A box for each service, arrows between them, latency on every edge. It feels like magic, and — more dangerously — it feels complete . "The agent traces everything" is the sentence repeated in every onboarding doc. This is the story of the moment that sentence stopped being true on my platform, why I'm glad it did, and the difference between a system that is working and a system you can actually see . The flow everyone trusts The platform is an event-driven set of Spring Boot services: an API gateway in front, a user-service backed by MySQL, a notification-service backed by PostgreSQL, and Kafka carrying events between them. A user is created, an event is published, a notification is sent. I didn't want to draw that topology. A hand-drawn architecture diagram is documentation that drifts — true the day you commit it, slightly wrong a month later, actively misleading after a quarter. I wanted the dependency graph generated from live traffic , so it would always reflect what the system actually does. Grafana Tempo does exactly this. Its service-graphs processor reads matched client/server span pairs out of trace data and emits a metric — traces_service_graph_request_total — that Grafana renders as a node graph. No edge is ever wired by hand. The topology is derived, continuously, from real spans. The edge that wasn't there I generated the graph and the synchronous edges lit up immediately: api-gateway → user-service user-service → MySQL notification-service → PostgreSQL Then I looked for the one edge I actually cared about — user-service → notification-service , the asynchronous hop over Kafka. It wasn't there. The naive conclusion (and why it's wrong) The tempting read is immediate and obvious: the async hop is broken. The event isn't getting across. Go debug the consumer. So I checked. And the consumer was completely fine. notification

2026-08-10 原文 →
AI 资讯

Building a Production AI Agent in Spring Boot: The LLM Judge That Scores Your Agent (Part 8)

Last week I ran a demo of the agent for a colleague who was deciding whether to bet a feature on it. The approval gate from Part 7 worked exactly as designed. The agent searched, added to cart, asked for the address, and stopped at the confirmation link. My colleague nodded and asked one question: "OK, but is it actually good?" I did not have an answer. I had 31 passing tests from Part 6, which prove the agent is bug-free. I had a state machine, which proves it cannot place an order without a human. Neither of those proves the agent answers customers well. A bug-free agent can still tell a customer the shop ships within two days when the shipping partner takes five. No unit test catches that, because no unit test reads the answer. That is the gap this part closes. Part 7 ended with a promise: the next part would build an evaluation harness, so "is it good" stops being a feeling and becomes a score. This is that part. I built an LLM-as-a-judge harness for the same e-commerce agent as Parts 1 through 7: same nine tools, same supervisor, same memory. It runs 40 real conversations from production logs against five metrics every night and prints a score for each one. The first run was uncomfortable, and that is exactly why it exists. I am a Senior Software Engineer II at BS23 in Dhaka, and I have been building production AI agents with Spring Boot and Spring AI for over a year. Everything below is the harness as I actually run it. The Difference Between Tested and Good Part 6 tested the agent without an LLM: 31 tests, zero model calls, asserting on tool calls, services, and the order state machine. That suite answers "did the agent call the right tool, in the right order, with the right arguments?" It cannot answer "was the answer right?" because you cannot write an assertion for an LLM's wording. Evaluation is a different layer. You cannot assert on the answer, but you can judge it, and you can use an LLM to do the judging. Spring AI documents this pattern in its LLM-as

2026-08-09 原文 →
AI 资讯

Spring Boot For Beginner

🚀 Building a REST API with Java Spring Boot: A Practical Beginner’s Guide If you're coming from Java and want to move into backend development, Spring Boot is one of the best frameworks to learn. It removes a lot of the boilerplate traditionally associated with Spring and makes it surprisingly easy to build production-ready REST APIs. In this article, we'll build a simple Blog REST API using: ☕ Java 🌱 Spring Boot 🌐 Spring Web 🗄️ Spring Data JPA 🐘 PostgreSQL 📦 Maven 🧪 Postman By the end, we'll have an API that can: Create a blog post Get all blog posts Get a post by ID Update a post Delete a post 1. What is Spring Boot? Spring Boot is a framework built on top of the Spring Framework that makes it easier to create Java applications. Without Spring Boot, you often need to configure many things manually. Spring Boot gives us: Auto-configuration Embedded servers Starter dependencies Production-ready features Easy REST API development A simple Spring Boot application can be started with: @SpringBootApplication public class BlogApplication { public static void main ( String [] args ) { SpringApplication . run ( BlogApplication . class , args ); } } That's enough to start our application. 2. Create the Spring Boot Project The easiest way to create a Spring Boot project is through Spring Initializr . Choose: Project: Maven Language: Java Spring Boot: Latest stable version Packaging: Jar Java: 17+ Add these dependencies: Spring Web Spring Data JPA PostgreSQL Driver Validation Lombok Your project structure will look something like: src └── main └── java └── com.example.blog ├── BlogApplication.java ├── controller ├── service ├── repository ├── entity └── dto This separation will become important as our application grows. 3. Create the Blog Entity Let's create a simple BlogPost entity. @Entity @Table ( name = "blog_posts" ) public class BlogPost { @Id @GeneratedValue ( strategy = GenerationType . IDENTITY ) private Long id ; @NotBlank private String title ; @NotBlank @Column (

2026-08-08 原文 →
AI 资讯

Java Spring Boot Logging: Log Levels, Logback, JSON Logs & Production Best Practices

Production-Grade Logging in Spring Boot: A Complete Guide to Logging Levels, Files, JSON Logs, Correlation IDs, and Best Practices Logging is one of the most important parts of a production backend system. When everything works, you may not think much about logs. But when production starts returning 500 errors at 2 AM, a customer reports that an API is failing, or a payment request behaves unexpectedly, logs become one of your most important debugging tools. Poor logging makes production debugging painful. Good logging helps you answer: What happened? When did it happen? Which user triggered it? Which request caused it? Which service handled it? How long did it take? What failed? Why did it fail? What should we investigate next? In this article, we will build a production-grade logging strategy for a Java Spring Boot application . 1. What Does Production-Grade Logging Mean? Production-grade logging is not simply: log . info ( "User created" ); Production logging should be: Structured Searchable Consistent Secure Configurable Environment-aware Correlated across requests Useful during debugging Suitable for monitoring and alerting A good logging architecture might look like this: Spring Boot Application | v Logback | +---- application.log | +---- error.log | +---- audit.log | +---- access.log | v Log Aggregation | +---- ELK +---- Grafana Loki +---- CloudWatch +---- Datadog +---- Splunk The goal is not to log everything. The goal is to log the right information at the right level . 2. Understanding Log Levels Spring Boot uses SLF4J as the logging abstraction and commonly uses Logback as the underlying logging implementation. The most common log levels are: TRACE DEBUG INFO WARN ERROR The order represents increasing severity. TRACE TRACE is the most detailed logging level. Example: log . trace ( "Entering calculateInvoice() with customerId={}" , customerId ); Use TRACE for very detailed diagnostic information. Usually: Production: OFF Development: Sometimes ON Debugging

2026-08-08 原文 →
AI 资讯

I Built a Self-Hosted AI Support Widget with Spring Boot (No Monthly SaaS Fees)

Every new SaaS seems to embed ChatGPT these days. Most AI support solutions rely on third-party platforms, monthly subscriptions, and vendor lock-in. While they're great products, I wanted something different. I wanted complete ownership. I wanted to deploy everything on my own server, use my own OpenAI API key, customize every part of the experience, and embed the widget into any website with a single script tag. So I built my own self-hosted AI support widget using Spring Boot and Vanilla JavaScript. Why I Built It When building small products and websites, I realized that customer support quickly becomes a problem. Users have questions about pricing, features, returns, or simply get stuck. Most developers solve this by integrating services like Intercom, Crisp, or Tidio. Those platforms are excellent, but they also mean: Monthly subscription costs Vendor lock-in Customer conversations stored on third-party platforms Limited customization Another external dependency I wanted something that developers could completely own. The Goal The goal was simple. Build an AI-powered customer support widget that developers can deploy on their own server and integrate into any website in less than a minute. The widget should: Answer customer questions using AI Learn from a custom knowledge base Match the company's branding Store conversation history Allow human handoff Be easy to deploy Require only one script tag to embed Technology Stack Java 17 Spring Boot 3 Spring Security Spring Data JPA Thymeleaf Vanilla JavaScript H2 Database (MySQL supported) OpenAI API Architecture The overall architecture is intentionally simple. Visitor │ ▼ AI Chat Widget (Vanilla JavaScript) │ ▼ Spring Boot REST API │ ▼ OpenAI API │ ▼ Database (H2 / MySQL) Keeping the frontend framework-free makes the widget lightweight and easy to embed into virtually any website. One-Line Integration Adding the widget to a website only requires a single script. <script src="/widget/widget.js" data-api-base=""></sc

2026-08-07 原文 →
AI 资讯

I used Spring Boot daily but never really understood what happened after pressing Enter in Postman.

Most of us use Spring Boot every day. We create a @RestController, run the application, hit an endpoint from Postman, and get a response. But have you ever wondered what actually happens between clicking "Send" in Postman and your controller method executing? When I started digging into Spring internals, I realized there are several layers working together before my controller is even called. Here's the high-level request flow: Postman │ ▼ Operating System │ ▼ Embedded Tomcat │ ▼ Servlet Filter Chain │ ▼ Spring Security (JWT) │ ▼ DispatcherServlet │ ▼ Controller │ ▼ Service │ ▼ Repository │ ▼ Database What surprised me? One thing I misunderstood for a long time was thinking that the request directly reaches my controller. In reality: The Operating System first routes the request to the application listening on the target port (for example, 8080). Embedded Tomcat accepts the connection. The request passes through the Servlet Filter Chain. Spring Security validates the JWT (if security is enabled). Only after successful authentication does the request reach Spring MVC's DispatcherServlet, which finds the correct controller. This means your controller only executes after several infrastructure components have already processed the request. Key Takeaway Understanding this request flow makes Spring Boot feel much less "magical." Instead of memorizing annotations, you begin to understand why they work. In the next post, I'll explain how Spring Boot starts Embedded Tomcat automatically before the first request even arrives.

2026-08-04 原文 →
AI 资讯

7 Production Issues Every Spring Boot Developer Should Learn Before Becoming Senior

After working on enterprise applications and distributed microservices, I have realized that the biggest challenges rarely come from writing business logic. They come from handling production traffic, failures, concurrency, and unexpected edge cases. Here are seven lessons that every Spring Boot developer should know before calling themselves a senior engineer. 1. Never Assume an API Will Be Called Only Once One of the most common mistakes is assuming a client sends exactly one request. In reality: Users refresh the page. Mobile apps retry automatically. API gateways retry requests. Kafka consumers may reprocess events. Network failures cause duplicate submissions. If your endpoint creates an order, payment, or booking every time it receives a request, duplicates are almost guaranteed. Better Approach Design APIs to be idempotent . For example: Use an Idempotency-Key. Store processed request IDs. Ignore duplicate requests safely. Production systems should always expect duplicate requests. 2. Database Transactions Are Not Enough Many developers believe this solves everything: @Transactional public void createOrder () { ... } It doesn't. A transaction protects changes inside a single database . It does not protect: Kafka publishing Email sending External REST APIs Redis updates File uploads If your database commits successfully but Kafka publishing fails, your system is already inconsistent. Better Approach Use patterns such as: Transactional Outbox Saga Pattern Event-driven architecture Retry with dead-letter queues 3. Don't Trust External APIs Every external service will eventually fail. Your payment provider. Your authentication service. Your notification service. Even your own internal microservices. Never assume another service is always available. Add Protection Timeouts Retries Circuit Breakers Fallback logic Monitoring Failing fast is usually better than waiting forever. 4. Logging Is More Valuable Than You Think When production goes down, nobody asks: "Was th

2026-08-04 原文 →