Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
Spring Service or Util for a generator class in Java?

I have barcode generator methods that I call from Controller in my Java (Spring Boot) project. The generator class is as shown below:

@Component
@NoArgsConstructor
public class QRCodeGenerator {
    private static final int LABEL_X_POS = 45;
    private static final int LABEL_Y_POS = 20;

    @Value("${qr-code.margin}")
    private int margin;

    @Value("${qr-code.fontSize}")
    private int fontSize;

    public ResponseEntity<Resource> getQRCode(String data) throws IOException {
        
        // code omitted for brevity
        
        addLabel(image, label);        
        final ByteArrayResource resource = new ByteArrayResource(toByteArray(image));
        return ResponseEntity.ok().body(resource);
    }

    private static byte[] toByteArray(BufferedImage image) throws IOException {
        // code omitted for brevity
    }

    private void addLabel(BufferedImage source, String text) {
        int x = LABEL_X_POS;
        int y = LABEL_Y_POS;
        // code omitted for brevity
    }
}

First I started to use this class as static, but then I removed static to read the data in application.yml properly.

Here is some points that I need to be clarified:

1. I am new in Spring and as far as I see, spring services are generally used to provide data from database or any other service, endpoints, etc. Is that true?

2. Should I create a service for the class above (I do not need to access to database in that class)? Or it the approach is better (creating as a component and then injecting it to my Controller)?

3. There are many different opinions regarding to static Util classes. So, what about converting this class to a static Util class? Is it better than now or using it as a Spring Service?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Make it a spring service, and you will be able to substitute a mock for it easily when you write a test for the controller. Otherwise you will not be able to mock it (unless you use things like Powernock). Since you're already injecting values into it, it's a lot easier to keep this as a Spring component.

Generally it's a premature optimization to use static util classes and it can get in the way of testing. I would use static util classes only if they contain only static methods that have no side effects, which don't need access to configuration data and which I don't mind not being able to mock. The methods I use in input validation code would be an example of something I might use static methods for. But you have the most flexibility, for instance to be able to inject configurations, if you keep these as Spring components.

over 4 years ago · Santiago Trujillo Relatório

0

Here are some opinions on your questions:

  1. Classes annotated with @Service are used in business logic layer, it can provide data but it can also do actions as in your case.
  2. Based on the point 1. you can make it a service because that provides logic for creating qr codes for representation layer (Controllers).
  3. Having this kind of classes as @Component or more specific @Service makes it easier to inject dependencies using Dependency Injection and also it's easier to inject your class as dependency to other beans so it's easier also to test/mock. Keeping it as Spring Service is a better approach.
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda