Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
One plan-mode prompt, five new files and five changed ones: Comment, CommentRepository, CommentService, CommentController and the comments on post.html. The review checks th:text, the owner-or-admin delete in the service and the rule order; 43 tests pass, and Noah's hand-made delete still gets a 403.
What you will learn
- Run the agent loop on a real feature: plan, diff, review, test, commit
- Write a plan-mode prompt with context, task, rules and format
- Read the five files the agent added, layer by layer
- Check the edge cases yourself: a hidden button, a direct POST and HTML in a comment
Before you start
- Plan Before Code
- Reading an AI Agent's Diff
- Fixing the Access Bugs: a Rule per Role and an Ownership Check
This time one whole feature, comments on posts, is built by the AI agent from a single prompt, and we check each step. It touches every layer of the blog, so it's a good test of everything before it: the brief, the plan, reading the diff, the security rules, and the tests.
The agent loop
- Plan. The prompt asks for the files and the tests first, then a stop.
- Diff. Five new files, five changed ones, nothing else.
- Review. Comments use
th:text, the delete check is in the service, and the new URL rule sits before/posts/**. - Test.
./mvnw test: 43 tests green, five of them for comments. Then a look in the browser. - Commit. Four small commits, done by hand.
The prompt
TASK
Add comments to posts.
- A Comment has text (max 500), an author Account, the Post and createdAt.
- Logged-in users comment on a post page (POST /posts/{id}/comments); visitors see "Log in to comment".
- A comment can be deleted by its author or an ADMIN (POST /comments/{id}/delete), the same check style as getForEdit.
- Comments are shown oldest first, always with th:text - never th:utext.
- Seed 2-3 comments.
RULES
- Constructor injection, small classes, the style of the existing code. No new dependencies.
- Every new URL gets a rule in SecurityConfig, before the public /posts/** rule.
- Tests like the existing ones (@SpringBootTest + MockMvc, user(...).roles(...), csrf()): a visitor is sent to
login, Emma comments, Noah cannot delete Emma's comment (403), the admin can, <b> stays text.
FORMAT
1) PLAN: the files you will add or change, one line each, and the tests by name. Then STOP and wait for my OK.
2) After my OK: entity and repository, service, controller, page, security rule, tests - and tell me what to check
after each step.
Above these sit a ROLE ("plan first, change only what the plan says, do not commit") and a CONTEXT block naming the stack, the three demo accounts and which posts are whose, and pointing at PostService.getForEdit as the rule to copy. It's the five-part brief applied to a real feature, with the edge cases written as tests.
Comment and its repository
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 500)
private String text;
@ManyToOne
private Account author;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE) // a deleted post takes its comments with it
private Post post;
private LocalDateTime createdAt;
protected Comment() {
}
public Comment(String text, Account author, Post post, LocalDateTime createdAt) {
this.text = text;
this.author = author;
this.post = post;
this.createdAt = createdAt;
}
// getters
}
Many comments, one account; many comments, one post. @OnDelete(CASCADE) means that when a post is deleted, its comments go with it. The repository is one interface with one derived query, findByPostOrderByCreatedAtAsc(Post post): this post's comments, oldest first.
CommentService: the rules
public Comment add(Long postId, String text, String email) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
Account author = accountRepository.findByEmail(email).orElseThrow();
return commentRepository.save(new Comment(text.strip(), author, post, LocalDateTime.now()));
}
// the same rule as PostService.getForEdit: the author or an ADMIN. Returns the post id, for the redirect.
public Long delete(Long commentId, Authentication user) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
boolean owner = comment.getAuthor().getEmail().equals(user.getName());
boolean admin = user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
if (!owner && !admin) {
throw new AccessDeniedException("You can only delete your own comments");
}
commentRepository.delete(comment);
return comment.getPost().getId();
}
Adding finds the post (404 if there's none) and the author by the logged-in email, strips the text and stamps the time. Deleting copies getForEdit: owner or admin, otherwise AccessDeniedException and a 403.
CommentController and post.html
@PostMapping("/posts/{id}/comments")
public String add(@PathVariable Long id, @RequestParam String text, Authentication user,
RedirectAttributes redirect) {
if (text.isBlank() || text.length() > CommentService.MAX_LENGTH) {
redirect.addFlashAttribute("commentError", "A comment is 1 to 500 characters");
} else {
commentService.add(id, text, user.getName());
}
return "redirect:/posts/" + id + "#comments";
}
@PostMapping("/comments/{id}/delete")
public String delete(@PathVariable Long id, Authentication user) {
Long postId = commentService.delete(id, user);
return "redirect:/posts/" + postId + "#comments";
}
Two URLs. An empty comment or one over 500 characters gets a short message and nothing is saved. Delete hands the decision to the service, then goes back to the comments on the post. SecurityConfig gets .requestMatchers("/posts/*/comments", "/comments/**").hasAnyRole("USER", "ADMIN") above the public rule.
<article class="comment" th:each="comment : ${comments}">
<div class="comment-meta">
<strong th:text="${comment.author.name}">Noah Patel</strong>
<span th:text="${#temporals.format(comment.createdAt, 'MMMM d, yyyy HH:mm')}">June 12, 2024 18:05</span>
</div>
<!-- th:text, never th:utext: a comment is plain text, so <b> shows as <b> -->
<p th:text="${comment.text}">Nice to see the posts coming from the database now.</p>
<form th:if="${#authentication.name == comment.author.email or #authorization.expression('hasRole(''ADMIN'')')}"
th:action="@{/comments/{id}/delete(id=${comment.id})}" method="post"
onsubmit="return confirm('Delete this comment?');">
<button class="link-button" type="submit">Delete</button>
</form>
</article>
The text uses th:text, never th:utext, so a <b> tag shows as text and never runs. The delete form shows only for the author or an admin. Logged-in users see the comment form; visitors get "Log in to comment".
Check the edge cases yourself
Emma comments on post 1: the rule sees a user, the service finds the post and Emma, and the new comment is saved with id 4 (the insert into the comment table is in the log), then a 302 back to the post. Who may delete comment 5, which Emma wrote? Emma, as the owner: 302. Chaand, as an admin: yes. Noah: owner false, admin false, 403. Noah has no delete button on his page, so he sends the POST himself, and the service still says no.
The answers the app gave: a visitor's comment is a 302 to the login page; Emma's comment is saved; her comment with a <b> tag shows as plain text, not bold; Noah's delete of Emma's comment is a 403; Emma's own delete is a 302 and the comment is gone. The agent wrote the code. The plan, the review, the tests and these checks are still yours.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
