Home > Software design >  How to check constraints before creating an object using Spring?
How to check constraints before creating an object using Spring?

Time:08-11

I write my own unit converter. I have Measure.class, which have fields BigDecimal value and Unit unit (Unit.class is my own abstract class with many implementations, which means e.g. meter, inches, kelvin etc)

@Component
@Getter
@Setter
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Measure {
    BigDecimal value;
    Unit unit;

    public Measure(BigDecimal value, Unit unit) {
        this.value = value;
        this.unit = unit;
    }
}

Also I've created abstract MeasureConstraint.class with check() method and a lot of it's implemetations (like TemperatureConstraint.class). check() method should be called when object Measure created.

What do I want to get, for example:

Measure measure = new Measure (5, *Kelvin*); // OK
Measure measure = new Measure (-5, *Kelvin*); // exception, Kelvin should be 0 or greater

I've tried to insert field List<MeasureConstraint> constraints to the Measure.class (and add this field to constructor parameters for @Autowired), filter by type this list to get needed constraint and call it's check() method in constructor.

But this solution makes it impossible for me to simple create Measure objects by myself (not using Spring) at the other classes in my application, because now I must create by myself List<MeasureConstraint> constraints too (I understand that Spring does not work in this situation). The reason I need to create Measure object by myself is because I need to create temporary variable during the conversion process.

I just started learning Spring and do not completely understand conceptions of IoC and DI. Maybe I shouldn't use manual object creation ever and nowhere if I'm using Spring? Should I inject all temporary variables as fields of my Converter.class and use them in `convert() method thus avoiding manual object creation? Please give me some advices.

Sory for my /Google translate/ English =)

CodePudding user response:

Perhaps you could create a separate class which would be responsible for creating Measure objects. There you could inject your MeasureConstraint beans and perform the logic of validating data before creating measures.

Something like that:

@Component
public class MeasureFactory {
    @Autowired // actually it's better to inject via constructor
    private List<MeasureConstraint> constraints;
    

    public Measure createMeasure(BigDecimal value, Unit unit) {
        // perform validation using constraints
        return new Measure(value, unit);
    }
}
  • Related