Why is the ZipValidator example a prototype bean

In the custom validator example the bean has prototype scope. But it has no state, so what is the point of the prototype scope?

I checked some of the other jmix validators and they seem to all have prototype scope, stateless or not. So perhaps it’s for consistency. Such design decisions deserve an extra line of in the documentation though.

Validator :: Jmix Documentation

Hi!

Thank you for your question.

Due to the design of the validator mechanism, all of them are declared as prototype spring bean.
First of all, this is necessary in order to have access to spring beans in the business logic of validators.

You are right that the ZipValidator from the documentation has no obvious reason to be a spring bean.

However, the validator creation mechanism uses a factory to create validator components. This factory creates all validators as prototype spring beans. This is why the validator from the documentation is a spring bean. Not only to comply with the concept.

If you try to use this validator in a standard workflow, but make it a regular Java class that is not a spring bean, you will get an error.

Best regards,
Dmitriy

1 Like

Thanks for your response, @d.kremnev .

However, my question wasn’t about why it needs to be a Spring bean. What I’m specifically asking is: why does it have to be declared with prototype scope instead of using the default singleton scope?

Thank you for clarifying the question.

If these validators were singleton scope beans:

  • All components would share the same validator instance
  • Changing validation parameters for one component would affect all other components using the same validator
  • It would create race conditions in concurrent scenarios

This design pattern is particularly important in a UI part of the framework where:

  • Multiple UI components might need the same type of validation but with different rules
  • Validation rules might need to be modified at runtime

Thus, the main reason for this design approach is the fact that for one instance of a component it is necessary to create a unique instance of the validator.

Best regards,
Dmitriy

Anyway, I agree with you that the example in the documentation is not very clear about these points. Moreover, the ZipValidator can easily be a singleton.

I created a task to add some state to the validator to justify its prototype scope:

Thank you

Regards,
Dmitriy

1 Like