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

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 does not change, so I want to keep it in a constant, but I still have to validate it to prevent clients from sending a wrong code.

Basically, what I want is the following:

@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 the Spring cache, but is it possible to do it with a constant?

    
asked by anonymous 23.08.2017 / 06:02

1 answer

0

I did the same question in the English OS and got the following #

response 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 in the constructor instead of using @Autowired in the field directly, as this makes @Service testable. You can also try to read the code in the method annotated with @PostConstruct , but I think it's best to do it in the constructor so you always have @Service in a ready-to-use state.

To use it on the rest of your% s of% s, inject the @Service instance into 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:

23.08.2017 / 18:47