Is it possible to have a constant populated through a Spring @Service?

Asked

Viewed 19 times

0

We have a web service that one of its parameters is called source and this source is always validated against a code in the database.

For each of our services, I have to validate this code. This code doesn’t change, so I want to keep it in a constant, but I still have to validate it to prevent customers from sending a wrong code.

Basically, what I want is this:

@Service
public class Service {

    @Autowired
    private LogBS logBS;

    // Eu sei que a palavra reservada "this" não pode ser utilizada em contexto estático.
    public static final Long CODIGO_LOG_WEB_SERVICE = this.logBS.recuperarCodigoLogWebService("webServiceName");

    public void validarCodigoOrigem(final Long origem) {
        if (!origem.equals(CODIGO_LOG_WEB_SERVICE)) {
            throw new ServiceException("Código de web service errado!");
        }
    }
}

I know something similar can be done with Spring cache, but it is possible to do it with a constant?

1 answer

0


I did the same question in the OS in English and I got the following reply translated and improved below:

I prefer the following way:

@Service
public class CodeValidatorServiceImpl implements CodeValidatorService {

    private final LogBS logBS;
    private final Long CODE;

    @Autowired
    public CodeValidatorServiceImpl(final LogBS logBS){
        this.logBS = logBS;
        CODE = this.logBS.retrieveLogWebServiceCode("webServiceName");
        if (CODE == null){
            throw new ServiceException("Code cannot be read from DB!");
        }
    }

    public void validateOriginCode(final Long origin) {
        if (!origin.equals(CODE)) {
            throw new ServiceException("Wrong origin code!");
       }
   }
}

A code review: I’d rather inject dependencies into the constructor than use @Autowired in the field directly, as this makes the @Service testable. You can also try to read the code in the annotated method with @PostConstruct, but I think it’s best to do it in the builder so that you always have the @Service in a state ready for use.

To use it in the rest of your @Services, enter the instance CodeValidatorService in them:

@Service
public class OtherService {

    private CodeValidatorService codeValidatorService;

    @Autowired
    public OtherService(CodeValidatorService codeValidatorService){
        this.codeValidatorService = codeValidatorService;
    }

    public void performAction(final Long origin) {
        codeValidatorService.validateOriginCode(origin);
        //do the rest of your logic here
   }
}

Official Spring References (in English):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.