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

推荐订阅源

WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
Latest news
Latest news
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Latest
Security Latest
宝玉的分享
宝玉的分享
S
Schneier on Security
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
N
Netflix TechBlog - Medium
P
Privacy & Cybersecurity Law Blog
L
LINUX DO - 热门话题
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Schneier on Security
Schneier on Security
博客园 - Franky
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
S
Secure Thoughts
T
Threat Research - Cisco Blogs
D
Docker
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
人人都是产品经理
人人都是产品经理
G
GRAHAM CLULEY
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 【当耐特】
PCI Perspectives
PCI Perspectives
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
V
Vulnerabilities – Threatpost
F
Fortinet All Blogs
罗磊的独立博客
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
SecWiki News
SecWiki News
A
Arctic Wolf
小众软件
小众软件
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Know Your Adversary
Know Your Adversary

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
CLAUDE.md for Spring Boot: 13 Rules That Make AI Write Production-Ready Java Web Applications
Olivia Craft · 2026-05-18 · via DEV Community

CLAUDE.md for Spring Boot: 13 Rules That Make AI Write Production-Ready Java Web Applications

Spring Boot is the framework where AI assistance produces the widest range of output quality.

On one end: AI that follows Spring idioms, uses constructor injection, writes proper layered architecture, and generates code a senior Java engineer would approve. On the other end: AI that uses field injection everywhere, puts business logic in controllers, ignores transaction boundaries, and generates N+1 queries with JPA.

The difference between these outcomes isn't the model. It's whether you've defined what "correct Spring Boot" means for your project.

These 13 rules cover the patterns that matter most — the ones where AI consistently drifts without explicit instruction.


Rule 1: Constructor injection only — no field injection

Dependency injection: constructor injection exclusively.
Banned: @Autowired on fields. @Autowired on setters.
Required: final fields. All dependencies injected via constructor.
Use: Lombok @RequiredArgsConstructor to reduce boilerplate.

Enter fullscreen mode Exit fullscreen mode

Field injection is the single most common AI-generated Spring anti-pattern. It makes classes untestable without a Spring container, hides dependencies, and creates circular dependency problems that surface at runtime.

// Banned — field injection
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;  // Hidden dependency, untestable
}

// Required — constructor injection
@Service
@RequiredArgsConstructor
public class OrderService {
    private final OrderRepository orderRepository;  // Explicit, testable, immutable
}

Enter fullscreen mode Exit fullscreen mode

Constructor injection makes every dependency explicit. The class can be instantiated in a unit test with new OrderService(mockRepository) without any Spring context.


Rule 2: Layered architecture — controller, service, repository, domain

Architecture layers (strict separation):
- @RestController: HTTP only — request mapping, validation, response shaping.
- @Service: business logic. No HTTP types. No JPA entity graph decisions.
- @Repository: data access. JPA queries, JDBC, caching.
- Domain: POJOs / records. No Spring annotations.
- Cross-layer: use DTOs. Never pass JPA entities to controllers.

Enter fullscreen mode Exit fullscreen mode

AI puts business logic in controllers because it's the fastest path to a working endpoint. This produces controllers with 200 lines of logic that can't be tested without HTTP infrastructure.

// Wrong — business logic in controller
@PostMapping("/orders")
public ResponseEntity<Order> createOrder(@RequestBody OrderRequest req) {
    // 50 lines of business logic here
    if (inventory.getStock(req.getProductId()) < req.getQuantity()) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Insufficient stock");
    }
    // ...
}

// Right — controller delegates to service
@PostMapping("/orders")
public ResponseEntity<OrderResponse> createOrder(@Valid @RequestBody OrderRequest req) {
    OrderResponse order = orderService.createOrder(req);
    return ResponseEntity.status(HttpStatus.CREATED).body(order);
}

Enter fullscreen mode Exit fullscreen mode


Rule 3: DTOs for every API boundary — never expose JPA entities

API contracts:
- Request: dedicated request DTO with @Valid validation annotations.
- Response: dedicated response DTO. Never return @Entity classes.
- Mapping: MapStruct for DTO-entity mapping. No manual getters/setters chains.
- Records: use Java records for immutable DTOs where appropriate.

Enter fullscreen mode Exit fullscreen mode

Exposing JPA entities from REST controllers leaks database structure, creates circular serialization issues with bidirectional relationships, and makes schema changes break API contracts.

// Banned — entity in response
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id).orElseThrow();  // Exposes everything
}

// Required — response DTO
public record UserResponse(Long id, String email, String displayName) {}

@GetMapping("/users/{id}")
public UserResponse getUser(@PathVariable Long id) {
    User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", id));
    return userMapper.toResponse(user);
}

Enter fullscreen mode Exit fullscreen mode


Rule 4: Transaction boundaries in the service layer

Transactions:
- @Transactional on service methods, not controllers or repositories.
- Read-only queries: @Transactional(readOnly = true) — enables query optimizations.
- Never @Transactional on repository methods for business operations.
- Checked exceptions do NOT trigger rollback by default — use rollbackFor if needed.
- No @Transactional on private methods — Spring AOP won't intercept them.

Enter fullscreen mode Exit fullscreen mode

AI generates @Transactional wherever it sees database access, including on private methods where it has no effect, and on controllers where it creates unnecessarily long transactions.

// Wrong — @Transactional on private method (no effect)
@Service
public class PaymentService {
    @Transactional
    private void processPayment(Order order) { ... }  // AOP proxy can't intercept this
}

// Right — transaction on public service method
@Service
public class PaymentService {
    @Transactional(rollbackFor = PaymentException.class)
    public PaymentResult processPayment(Long orderId) {
        Order order = orderRepository.findById(orderId).orElseThrow();
        // business logic
    }

    @Transactional(readOnly = true)
    public List<PaymentSummary> getPaymentHistory(Long userId) { ... }
}

Enter fullscreen mode Exit fullscreen mode


Rule 5: JPA — explicit fetch strategies, no lazy loading surprises

JPA fetch strategy:
- Default all associations to LAZY. Never EAGER on @ManyToOne or @OneToMany.
- Load what you need via JPQL JOIN FETCH or @EntityGraph.
- No accessing lazy collections outside a transaction (LazyInitializationException).
- Named queries or Spring Data specifications for complex queries.
- Pagination: always use Pageable — never load unbounded collections.

Enter fullscreen mode Exit fullscreen mode

EAGER loading is the JPA equivalent of N+1 — it fetches everything whether you need it or not, at the cost of joins on every query.

// Banned — EAGER by default (fetches User on every Order query)
@ManyToOne(fetch = FetchType.EAGER)
private User user;

// Required — LAZY, explicit when needed
@ManyToOne(fetch = FetchType.LAZY)
private User user;

// Load explicitly in the query that needs it
@Query("SELECT o FROM Order o JOIN FETCH o.user WHERE o.status = :status")
List<Order> findByStatusWithUser(@Param("status") OrderStatus status);

Enter fullscreen mode Exit fullscreen mode


Rule 6: Validation at the boundary — Bean Validation on DTOs

Validation:
- All input validation via Bean Validation annotations on DTOs (@NotNull, @Size, @Email, @Pattern).
- @Valid on controller method parameters — triggers validation automatically.
- @Validated on service beans for method-level validation.
- Custom validators: implement ConstraintValidator for business rules.
- Never validate in service layer what can be validated at the boundary.

Enter fullscreen mode Exit fullscreen mode

public record CreateUserRequest(
    @NotBlank @Email String email,
    @NotBlank @Size(min = 8, max = 100) String password,
    @NotBlank @Size(min = 2, max = 50) String displayName
) {}

@PostMapping("/users")
public ResponseEntity<UserResponse> createUser(@Valid @RequestBody CreateUserRequest req) {
    // req is guaranteed valid here — no manual null checks needed
    return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(req));
}

Enter fullscreen mode Exit fullscreen mode


Rule 7: Exception handling via @ControllerAdvice — no scattered @ExceptionHandler

Error handling:
- Global exception handler: one @RestControllerAdvice class.
- Typed exception hierarchy: domain exceptions extend RuntimeException.
- Standard error response shape: { error, message, path, timestamp }.
- Never catch Exception broadly in service layer without rethrowing.
- HTTP status mapping in the advice class, not in service or repository.

Enter fullscreen mode Exit fullscreen mode

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(ResourceNotFoundException ex, HttpServletRequest req) {
        return new ErrorResponse("not_found", ex.getMessage(), req.getRequestURI());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
        String message = ex.getBindingResult().getFieldErrors().stream()
            .map(e -> e.getField() + ": " + e.getDefaultMessage())
            .collect(Collectors.joining(", "));
        return new ErrorResponse("validation_failed", message, req.getRequestURI());
    }
}

Enter fullscreen mode Exit fullscreen mode


Rule 8: Configuration via @ConfigurationProperties — not @Value scattered everywhere

Configuration:
- Group related config in @ConfigurationProperties classes.
- Validate with @Validated + Bean Validation annotations.
- No @Value on individual fields across multiple classes.
- Profiles: application-{profile}.yml for environment differences.
- Secrets: externalize via environment variables or secret manager — never in application.yml.

Enter fullscreen mode Exit fullscreen mode

@ConfigurationProperties(prefix = "app.payment")
@Validated
public record PaymentConfig(
    @NotBlank String apiKey,
    @NotNull @Min(1) Integer timeoutSeconds,
    @NotBlank String webhookSecret
) {}

Enter fullscreen mode Exit fullscreen mode


Rule 9: Security — Spring Security properly configured

Security:
- Explicit SecurityFilterChain bean — no WebSecurityConfigurerAdapter (deprecated Spring Boot 3+).
- CSRF: disabled for stateless REST APIs using JWT. Enable for session-based apps.
- CORS: configure via CorsConfigurationSource bean, not annotations on controllers.
- Password encoding: BCryptPasswordEncoder only. Never store plain text or MD5.
- Method security: @PreAuthorize on service methods for business-level authorization.

Enter fullscreen mode Exit fullscreen mode

AI still generates WebSecurityConfigurerAdapter (removed in Spring Boot 3) and forgets to configure CORS when the frontend is on a different origin.


Rule 10: Testing — slice tests, not full context loads

Testing strategy:
- Unit tests: plain JUnit 5 + Mockito. No Spring context. Constructor injection makes this trivial.
- Web layer: @WebMvcTest for controllers. Mocks the service layer.
- Data layer: @DataJpaTest with H2 or Testcontainers for repositories.
- Integration: @SpringBootTest(webEnvironment = RANDOM_PORT) for full stack only.
- Never use @SpringBootTest for unit or slice tests — it's 10x slower.

Enter fullscreen mode Exit fullscreen mode

// Web layer test — fast, no full context
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean OrderService orderService;

    @Test
    void createOrder_validRequest_returns201() throws Exception {
        given(orderService.createOrder(any())).willReturn(sampleOrderResponse());
        mockMvc.perform(post("/orders").contentType(APPLICATION_JSON).content(validOrderJson()))
            .andExpect(status().isCreated());
    }
}

Enter fullscreen mode Exit fullscreen mode


Rule 11: Actuator and observability — configure from the start

Observability:
- Spring Boot Actuator: enabled with health, info, metrics endpoints.
- Health checks: custom HealthIndicator for external dependencies (DB, cache, external API).
- Metrics: Micrometer with Prometheus registry.
- Logging: structured JSON logging in production (logstash-logback-encoder).
- Correlation IDs: MDC for request tracing across log lines.

Enter fullscreen mode Exit fullscreen mode


Rule 12: Async operations — @async with explicit executors

Async:
- @EnableAsync on configuration class.
- @Async methods: dedicated @Bean ThreadPoolTaskExecutor — not the default SimpleAsyncTaskExecutor.
- Return CompletableFuture<T> from async methods, not void (for error handling).
- Never call @Async methods from the same class — Spring AOP proxy won't intercept.
- Scheduled tasks: @Scheduled with fixedDelay or cron, with @EnableScheduling.

Enter fullscreen mode Exit fullscreen mode


Rule 13: The CLAUDE.md block for Spring Boot

## Spring Boot Standards

**Version:** Spring Boot 3.x | Java 21+ | Gradle (Kotlin DSL)

### Architecture
- Strict layering: Controller → Service → Repository → Domain
- DTOs at every API boundary — never expose @Entity directly
- MapStruct for DTO-entity mapping

### Dependency Injection
- Constructor injection only. @Autowired on fields is banned.
- Use Lombok @RequiredArgsConstructor to reduce boilerplate.

### JPA / Database
- All associations: FetchType.LAZY by default
- Explicit JOIN FETCH or @EntityGraph when loading associations
- @Transactional(readOnly = true) on all read-only service methods
- Always paginate with Pageable — no unbounded findAll()

### Validation & Errors
- Bean Validation (@Valid) on all request DTOs
- One @RestControllerAdvice for all exception handling
- Typed exception hierarchy extending RuntimeException

### Security
- SecurityFilterChain bean (not WebSecurityConfigurerAdapter)
- BCryptPasswordEncoder for passwords
- @PreAuthorize on service methods for authorization

### Testing
- Unit tests: JUnit 5 + Mockito, no Spring context
- Controller tests: @WebMvcTest
- Repository tests: @DataJpaTest + Testcontainers
- @SpringBootTest only for integration tests

Enter fullscreen mode Exit fullscreen mode


Why this matters for Spring Boot specifically

Spring Boot's "convention over configuration" model is powerful — and it means AI has strong defaults to lean on. The problem is those defaults aren't always the right ones for production.

EAGER fetch is the JPA default. Field injection works. WebSecurityConfigurerAdapter was the pattern for years. Business logic in controllers produces working code. None of these fail in development.

They fail when your database handles real load, when you need to write unit tests without starting a container, or when you upgrade Spring Boot and discover the deprecated APIs.

The CLAUDE.md block above defines what "Spring Boot done right" means for your project before AI generates a single line. The 15 minutes you spend writing it pays back on every controller, service, and repository the AI generates from then on.