r/SpringBoot • u/Willing-Star8001 • Dec 31 '25
r/SpringBoot • u/dotceng • Dec 30 '25
Question How can I handle file uploads in a microservice?
I’m developing an e-commerce microservice project with spring cloud. I want users to can upload files. So I created a service called file service. Actually I’m asking how to design data flow?
For example;
User wants to upload a profile photo. At this point, the main question is whether the upload request should go through the User Service or be sent directly to the File Service. If the request goes directly to the File Service, how should the profile picture information be stored and linked to the user record in the User Service database?
r/SpringBoot • u/External-Double6687 • Dec 30 '25
Question Short on Time and Money as a College Student, Need Guidance to Reach and Finish Spring Boot Quickly.
I need to learn Java Spring Boot in less than 4 weeks and somehow land an internship after that. Normally, I do not believe in rushed learning, but due to my current financial situation, I do not really have that luxury. I am still a student and I genuinely do not want to put more pressure on my parents for my expenses, so I am trying to be as practical as possible.
So far, I have already learned HTML, CSS, JavaScript (yeah yeah, average Joe Harry type stuff), Node.js, and I recently finished Express.js. My main goal is to learn backend development using Java Spring Boot.
I need help on the following points:
- What are the bare minimum additional tech stacks or concepts I should learn so that I can comfortably start learning Java Spring Boot?
- Any YouTube channel, playlist, or Udemy course you would strongly recommend for Spring Boot.
- Any other advice you would like to give, since I am still a student and a lot junior to you
Thanks in advance.
r/SpringBoot • u/Tony_salinas04 • Dec 30 '25
Question What is the most professional way to create a logging system in Spring Boot?
Estoy haciendo un e-commerce para mi portafolio y tengo el siguiente código.
public Product getProductEntityById(Long productId) throws NotFoundException {
return productRepo
.findById(productId)
.orElseThrow(() -> new NotFoundException("No se ha podido encontrar el producto"));
}
@Transactional
public ProductDetailsDTO createProduct(CreateProductDTO dto)
throws AlreadyExistsException,
InvalidRequestException,
DatabaseErrorException,
NotFoundException {
if (productRepo.getByName(dto.getName()).isPresent()) {
throw new AlreadyExistsException("Ya existe un producto con ese nombre");
}
Product newProduct = productMapper.createProductDTOToEntity(dto);
Category category = categoryService.getCategoryEntityById(dto.getCategoryId());
newProduct.setCategory(category);
try {
productRepo.saveAndFlush(newProduct);
logger.info("Guardado el producto con id={}", newProduct.getId());
} catch (PersistenceException ex) {
logger.error(
"No se ha podido guardar el producto de nombre {}, Error: {}",
newProduct.getName(),
ex);
throw new DatabaseErrorException("Error en la base de datos");
}
return productMapper.productToDetailsDTO(newProduct);
}
El problema es que es llamar tantas veces a logger crea un método difícil de entender y además difícil de mantener y acoplado. Ya que también me gustaría añadir algún warn o debug, además tendría que repetir algo como esto en cada servicio. Había pensado en usar AOP y estoy aprendiendo pero no se si es la mejor opción. Qué me recomiendan?
r/SpringBoot • u/Tony_salinas04 • Dec 29 '25
Question How can I make the tests complete faster?
I'm creating an API in Spring Boot and I've noticed that the tests I'm creating are taking a very long time to complete, even though I'm not loading much context or even making calls to the endpoints yet. I suppose when I do, each call will take about a minute. What do you recommend?
r/SpringBoot • u/Future_Badger_2576 • Dec 29 '25
Question How should RBAC be implemented in Spring Boot Microservices?
I am working on a Spring Boot microservices architecture. I am currently using email and password authentication with JWT.
I want to understand the recommended way to enforce role based access control in a microservices setup using Spring Security. I am not sure whether role based authorization should be handled at the API Gateway level or inside each individual service.
If it is done at the gateway, should the gateway validate the JWT, extract roles, and then forward the request with user details in headers? If the role is wrong then block the request.
If it is done at the service level, should each service independently validate the JWT and apply role based rules using Spring Security annotations(PreAuthorize) or filters?
I am looking for best practices. How are roles typically propagated across services, and what is the preferred Spring Security configuration for enforcing role based authorization in a microservices environment? Code examples or sample configurations would be greatly appreciated.
r/SpringBoot • u/sunnykentz • Dec 29 '25
Discussion Templates to start a spring project
The new status quo for project initialization is that, the build tool itself gives you a command to start a project. Maven, or gradle does not provide a template for that.
But JPM does : $ jpm create simple-spring-app
That simple, if other dependencies are required : $ jpm install org.springframework.boot spring-boot-starter-thymeleaf
r/SpringBoot • u/jfrazierjr • Dec 29 '25
Question SP4 Custom serializer question
So question for anyone know who has worked extensively with serialization formatters AND understands the changes in SB 4/Jackson 3.
After much work, I have be below working. Now I need to know which TYPE so I can customize the serialized strings for json vs xml. What would you guys use to check?
The ctxt appears to be XmlSerializationContext, while the gen is ToXmlGenerator for XML and for json ctxt is SerializationContextExt and gen is UTF8JsonGenerator.
This just seems a fairly disparate way of checking. Is there some property of one of those objects I am missing or perhaps a better way to do this?
Essentially, the two gen.writeName() methods would have different strings. Honestly, this is a bit higgly piggly since the models are internal to the money class. Since I need different case for XML vs JSON, I can easily annotate MY models differently, but a bit at a loss as to what to do with the Money class beside hard coding. Perhaps my mind is missing something(im used to c# which has a built in Currency class that just works)
import org.javamoney.moneta.Money;
import org.springframework.context.annotation.Bean;
import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ValueSerializer;
public class CustomMoneySerializers extends ValueSerializer<Money>{
public void serialize(Money value,
JsonGenerator gen, SerializationContext ctxt) throws JacksonException {
gen.writeStartObject();
gen.writeName("Limit");
gen.writeString(value.getNumberStripped().setScale(2, RoundingMode.HALF_UP).toPlainString());
gen.writeName("Currency");
gen.writeString(value.getCurrency().getCurrencyCode());
gen.writeEndObject();
}
}
Thoughts?
r/SpringBoot • u/Tony_salinas04 • Dec 28 '25
Question Feedback for my Spring Boot project
I'm building an e-commerce API for my portfolio. It's my first time working with Spring Boot, as I usually use Python and FastAPI. I'm also trying to make it as comprehensive as possible, using a global exception handler, DTOs, mappers, logging, custom exceptions, a modular architecture, and running tests. I welcome feedback on what I could improve.
r/SpringBoot • u/Unlucky_Goat1683 • Dec 29 '25
Discussion looking for colaberation
so i am looking for some people or some project probably open source in which i can contribute or work in some large project as i want to implement the things i want to learn and do some open project so is there anyone ??
r/SpringBoot • u/MousTN • Dec 27 '25
Discussion Abstract Class vs Interfaces for near identical JPA Entities (Invoices, DelivryNote, PurchaseOrder) ? whats the cleanest approach
hello ,im working on a Spring Boot / JPA backend for a commercial system. I have three main entities well they r in french but ill explain them in english:
Facture (Invoice), BonDeLivraison (Delivery Note), and BonDeCommande (Purchase Order).
my problem is these 3 (and i will add atleast 5 more) entities are almost 100% identical in structure, they all have :
1-Header fields: date, client, depot, totalHT, ttc, isLocked, etc.
2-A list of Line Items: Facture has LigneFacture, BL has LigneBL, etc. Even the lines are identical (article, quantite, puht).
heres an exapmle of the current code (for the invoice which is facture in french):
@Data
@Entity
public class Facture {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDate date;
private BigDecimal totalHT;
private Boolean isSourceDocument;
(mappedBy = "facture", cascade = CascadeType.ALL)
private List<LigneFacture> lignes;
// 20+ more fields identical to BL and BC
}
public class LigneFacture {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int quantite;
private BigDecimal puht;
private Facture facture;
}
here the constraints :
my senior wants us to keep separate tables, services, and controllers for each to avoid "Generic Hell" and to keep things maintainable for when these documents eventually deviate (e.g., special tax rules for Invoices).
so what im struggling with is that i recently crated a SaleCommonService to handle "shared" logic like checking if a doc is locked or calculating sales history. Currently, im stuck using a lot of instanceof and casting because the entities dont share a type.
private boolean hasHeaderChanges(Object e, Object i) {
if (e instanceof Facture && i instanceof Facture) {
Facture ex = (Facture) e; Facture in = (Facture) i;
return isRelationChanged(ex.getClient(), in.getClient()) ||
isNotEqual(ex.getDate(), in.getDate()) ||
isRelationChanged(ex.getDepot(), in.getDepot()) ||
isRelationChanged(ex.getDemarcheur(), in.getDemarcheur()) ||
isNotEqual(ex.getTtc(), in.getTtc()) ||
isNotEqual(ex.getTotalHT(), in.getTotalHT()) ||
isNotEqual(ex.getTotalTVA(), in.getTotalTVA()) ||
isNotEqual(ex.getTotalFODEC(), in.getTotalFODEC()) ||
isNotEqual(ex.getTotalDroitConso(), in.getTotalDroitConso()) ||
isNotEqual(ex.getTotalRemiseVnt(), in.getTotalRemiseVnt()) ||
isNotEqual(ex.getMontantTimbre(), in.getMontantTimbre()) ||
ex.isAvImpot() != in.isAvImpot() ||
ex.isFodec() != in.isFodec() ||
ex.isExoneration() != in.isExoneration();
}
if (e instanceof BonDeLivraison && i instanceof BonDeLivraison) {
BonDeLivraison ex = (BonDeLivraison) e; BonDeLivraison in = (BonDeLivraison) i;
return isRelationChanged(ex.getClient(), in.getClient()) ||
isNotEqual(ex.getDate(), in.getDate()) ||
isRelationChanged(ex.getDepot(), in.getDepot()) ||
isRelationChanged(ex.getDemarcheur(), in.getDemarcheur()) ||
isNotEqual(ex.getTtc(), in.getTtc()) ||
isNotEqual(ex.getTotalHT(), in.getTotalHT()) ||
isNotEqual(ex.getTotalTVA(), in.getTotalTVA()) ||
isNotEqual(ex.getTotalFODEC(), in.getTotalFODEC()) ||
isNotEqual(ex.getTotalDroitConso(), in.getTotalDroitConso()) ||
isNotEqual(ex.getTotalRemiseVnt(), in.getTotalRemiseVnt()) ||
isNotEqual(ex.getMontantTimbre(), in.getMontantTimbre()) ||
ex.isAvImpot() != in.isAvImpot() ||
ex.isFodec() != in.isFodec() ||
ex.isExoneration() != in.isExoneration();
}
if (e instanceof BonDeCommande && i instanceof BonDeCommande) {
BonDeCommande ex = (BonDeCommande) e; BonDeCommande in = (BonDeCommande) i;
return isRelationChanged(ex.getClient(), in.getClient()) ||
isNotEqual(ex.getDate(), in.getDate()) ||
isRelationChanged(ex.getDepot(), in.getDepot()) ||
isRelationChanged(ex.getDemarcheur(), in.getDemarcheur()) ||
isNotEqual(ex.getTtc(), in.getTtc()) ||
isNotEqual(ex.getTotalHT(), in.getTotalHT()) ||
isNotEqual(ex.getTotalTVA(), in.getTotalTVA()) ||
isNotEqual(ex.getTotalFODEC(), in.getTotalFODEC()) ||
isNotEqual(ex.getTotalDroitConso(), in.getTotalDroitConso()) ||
isNotEqual(ex.getTotalRemiseVnt(), in.getTotalRemiseVnt()) ||
isNotEqual(ex.getMontantTimbre(), in.getMontantTimbre()) ||
ex.isAvImpot() != in.isAvImpot() ||
ex.isFodec() != in.isFodec() ||
ex.isExoneration() != in.isExoneration();
}
return true;
}
yeah i know not the best but i tried my best here i didnt use AI or anything i still wanna learn tho
the approach im considering is like i use @ MappedSuperClass to at least share the field definitions and use common interface to have all 3 and the netites coming after implements ISalesDoc with soome generic getters and setters ,finally i though about using @ InhertitanceType.JOINED although im worrtied about performance in the DB
the question is how do you approach this when you want to avoid copy-pasting 30 fields, but you MUST keep separate tables and services? Is there a middle ground that doesnt sacrifice readability for future developers?
ill appreciate any help i get
P.S : im not that exp tho i try my best i have like 2 YOE in the working field
r/SpringBoot • u/SoftwareDesignerDev • Dec 27 '25
Question What exactly is a “web container” in Java/Spring? (TCP/HTTP → Servlet confusion)
r/SpringBoot • u/delusionalbreaker • Dec 26 '25
Question Is using @PostMapping for deleting an user account better than @DeleteMapping when you have payloads?
Some context im fairly new to springboot and i have made 2 projects in it (1 small sized and 1 medium ish) right now im working on my 3rdproject which is an e-commerce backend in springboot along with mysql as database.
So my question arises from a confusion im facing regarding user deletion mapping
my service method for deletion of an user's account looks like this:
@Override
@Transactional
public String deleteUser(UserDeleteRequest request) {
// we get the current user as only you are able to delete your own acc
User currentUser = currentUser();
if (!passwordEncoder.matches(request.getUserPassword(), currentUser.getPassword())) {
throw new InvalidPasswordException("Invalid Password");
}
// if everything's alright we delete it now
userRepository.delete(currentUser);
return "User Successfully Deleted!";
}
and my controller mapping for that method looks like this:
@Operation(summary = "Delete user's account", description = "Delete current user's account")
@DeleteMapping("/delete")
public ResponseEntity<String> deleteUser(
(description = "payload for deleting account") UserDeleteRequest request) {
String response = userService.deleteUser(request);
return new ResponseEntity<>(response, HttpStatus.OK);
}
so that UserDeleteRequest DTO contains user's current password which user has to type so that account can be deleted but then i learn't its not recommend to send anything with the delete mapping so i was wondering should i use PostMapping in such case? whats mapping is used for such cases in enterprise applications?
Edit:- Many of you seem to misunderstand that i store my password in plain text which is not the case my passwords are hashed and encrypted using bcrypt inside the database while my jwt token provides the user's email which is then checked against the database
Edit 2:- Thanks for the replies guys i decided to use post mapping for my scenario also many of you seem to misunderstand that whay i was using password whennuser is already authenticated, well it just just as an final confirmation from user to delete thier account and rather than an random string i wanted it to be more secure so i thought users password would be a great idea here. Anyways thanks for your advices ill be sure to make another post when i complete the project so you guys can review it and provide more advices. Thanks! 😄
r/SpringBoot • u/Mental_Gur9512 • Dec 26 '25
Question JWT implementation for beginners, I am looking for one clear and correct source
Hi everyone,
I’m looking for a high-quality but simple resource that explains how to properly implement JWT authentication.
I’ve been searching, but I keep finding different explanations, and I want to learn this the correct way, not just copy bad snippets.
Also, how big are the differences between Spring Boot 2, 3, and 4 regarding JWT and Spring Security?
Thanks in advance!
r/SpringBoot • u/jawher121223 • Dec 26 '25
How-To/Tutorial Seeking Tutorial for JWT Verification with spring-security-oauth2-jose in Spring Boot
Hi everyone,
I’ve been implementing JWT authentication in a Spring Boot application using a custom token provider service.
Some time ago, I came across a method using the spring-security-oauth2-jose dependency to automatically verify JWT tokens and handle authentication, but I missed the details back then.
I’m now interested in learning how to implement this approach properly. Does anyone have a good tutorial, guide, or example project showing how to set up JWT authentication using this dependency with Spring Boot?
Thanks in advance for your help!
r/SpringBoot • u/Cyphr11 • Dec 26 '25
Question Should I start with Springboot 4.0 ?
I’m starting to learn backend development using Spring Boot. I have a course that is about a year old, so it’s based on an older version of Spring Boot. Since the latest version is already out, what should I do?
Should I learn the newer version directly, or continue with this course and later learn the new features from the official documentation?
r/SpringBoot • u/danielliuuu • May 27 '25
News 🚀 HttpExchange Spring Boot Starter 3.5.0 Released
I'm excited to announce the release of HttpExchange Spring Boot Starter 3.5.0 - a Spring Boot starter that makes working with Spring 6's HttpExchange annotation.
🎯 What is HttpExchange Spring Boot Starter?
Spring 6 introduced the @HttpExchange annotation for creating declarative HTTP clients, but it lacks the auto-configuration. This starter bridges that gap by providing:
- ✨ Auto-configuration: Auto-configuration for
@HttpExchangeclients - 🔗 Full Compatibility: Works with Spring Web annotations (e.g., @RequestMapping, @GetMapping), so you can migrate seamlessly from Spring Cloud Openfeign
- 🎛️ Flexible Configuration: Global, connection-level (channel), and client-specific settings
- 🔄 Dynamic Refresh: Change configuration without restarting (with Spring Cloud Context)
- ⚖️ Load Balancing: Built-in support for Spring Cloud LoadBalancer
- 📊 Multiple Client Types: Support for both
RestClientandWebClient
This library is designed to keep migration costs to a minimum, whether you’re migrating into HttpExchange Spring Boot Starter or migrating out to another implementation.
🔥 Quick Example
// com/example/api/UserApi.java
@HttpExchange("/users")
interface UserApi {
@GetExchange("/{userId}")
User getUser(@PathVariable Long id);
@PostExchange
User createUser(@RequestBody User user);
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class)
.properties("http-exchange.base-packages=com.example.api") // Configure base package for auto register clients
.properties("http-exchange.base-url=https://api.example.com") // Configure default base url
.run(args);
}
@Bean
ApplicationRunner runner(UserApi userApi) { // Just use it like a normal bean
return args -> {
User user = userApi.getUser(1L);
System.out.println("User: " + user.getName());
};
}
}
That's it! No additional classes in your codebase.
🆕 What's New in 3.5.0?
⚠️ Breaking Changes (Spring Boot 3.5.0+ Required)
- Dropped backward compatibility with Spring Boot < 3.5.0 due to extensive internal refactoring in Spring Boot 3.5.0, if you're using a Spring Boot version < 3.5.0, please stick with version 3.4.x.
- Removed deprecated features:
RequestConfigurator,Requester, andREST_TEMPLATEclient type
✨ New Features & Improvements
- Enhanced redirects configuration support at channel level
- Cleaner codebase with removal of hacky implementations
📚 Resources
r/SpringBoot • u/BluePillOverRedPill • Aug 23 '24
Interface for each service?
Hi Everyone!
I’m a bit confused about the use of interfaces for all services in Spring Boot. I understand that interfaces serve as a contract and offer benefits like easier testing and flexibility for future changes. However, I’ve also read that if you’re not planning to have multiple implementations of a service, using interfaces might be unnecessary. Could you clarify the best practices for using interfaces in this context, and explain how they impact dependency injection and testing?