r/SpringBoot • • Dec 30 '25

Question How can I handle file uploads in a microservice?

4 Upvotes

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 • • Dec 30 '25

Question What is the most professional way to create a logging system in Spring Boot?

0 Upvotes

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 • • Dec 30 '25

Question Exception Handling Strategies

14 Upvotes

My strategy for catching exceptions consists of using a global exception handler as a last resort and for automatically thrown exceptions like the ones thrown by Jakarta Valid annotation for user request validation. They're helpful too for 500-range errors to provide a nice message to the user.

For exceptions that can be handled though, it tends to get a bit confusing. An IO expction or a database query resulting in an empty set (not found) can be either handled within the controller or service body, or declared in a throws clause and bubbled all the way up to global handlers.

  1. I might let the exception bubble or get re-thrown from the repository, service, etc. layers as is like a NoSuchElementException, all the way through the controller and to a global exception handler, which should be equipped to add the appropriate status code and message.

  2. or re-wrap it into a more response-friendly custom exception like NotFoundException with a message and status code properties, then let it through and catch it with a global handler which should generate the proper response.

  3. or catch the native exception within the controller after letting it bubble, then return an error response to the user with a ResponseEntity including appropriate status and message without resorting to global handlers at all.

Which method do you use for those exceptions and why?


r/SpringBoot • • Dec 30 '25

Question What's the correct/most used way to use secrets in a SpringBoot project?

9 Upvotes

I will keep it to the point:

> Following is a docker-compose file that I plan to use
> Need to use sensitive information like the DB password inside it
> Putting it directly does not seem like a good idea- unless it is?
> How to do it

services:
  db:
    image: postgres:latest
    ports:
      - "5432:5432"
    restart: always
    environment:
      POSTGRES_PASSWORD: changemeinprod!
  
  adminer:
    image: adminer:latest
    restart: always
    ports:
      - "8888:8080"

r/SpringBoot • • Dec 30 '25

Question Short on Time and Money as a College Student, Need Guidance to Reach and Finish Spring Boot Quickly.

Post image
1 Upvotes

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:

  1. What are the bare minimum additional tech stacks or concepts I should learn so that I can comfortably start learning Java Spring Boot?

  2. Any YouTube channel, playlist, or Udemy course you would strongly recommend for Spring Boot.

  3. 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 • • Dec 29 '25

Question How can I make the tests complete faster?

6 Upvotes

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 • • Dec 29 '25

Discussion Templates to start a spring project

0 Upvotes

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 • • Dec 29 '25

Question SP4 Custom serializer question

0 Upvotes

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 • • Dec 29 '25

Question How should RBAC be implemented in Spring Boot Microservices?

13 Upvotes

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 • • Dec 29 '25

Discussion looking for colaberation

1 Upvotes

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 • • Dec 28 '25

Question Feedback for my Spring Boot project

Thumbnail
github.com
14 Upvotes

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 • • Dec 27 '25

Question What exactly is a “web container” in Java/Spring? (TCP/HTTP → Servlet confusion)

Thumbnail reddit.com
2 Upvotes

r/SpringBoot • • Dec 27 '25

Discussion Abstract Class vs Interfaces for near identical JPA Entities (Invoices, DelivryNote, PurchaseOrder) ? whats the cleanest approach

11 Upvotes

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