MetadataTools/EntityStates null in JPA Entity

Hi

I am trying to get instance name of an entity like:

@Transient
@Autowired
MetadataTools metadataTools;

@DependsOnProperties(value = {"product", "currentDiscount"})
@JmixProperty
@Transient
public String getDiscountedProd() {
    if (discount != null && currentDiscount != null)
        return metadataTools.getInstanceName(product) + " (" + currentDiscount + ")";
    return null;
}

But metadataTools is null. Same is the case with EntityStates which I need in another entity class. Can’t I use these components in Jmix Entity class? Please suggest or I would have to define un-necessary InstanceName methods and call them.

Hi,

Generally speaking: dependency injection in entity classes is not possible.

But the case of the instance name method is special.

There you can declare MetadataTools as a parameter of the method and it will get injected when the method is invoked by the framework.

This should solve your problem :slight_smile:

Hi Mario

In @InstanceName methods, this works as mentioned in docs too but my methods are not InstanceName methods. Injection gives error in these methods :frowning:

I have about 4-5 such transient methods in 5 classes and most of them will make calculated values based on conditions.

Hi,

I mis-read your question, but it also works for entity instantiation via @PostConstruct. You can set the values in the transient field and then the getter will return the set value.

See: Entities :: Jmix Documentation

Generally I would advise you not overuse that mechanism. Instead probably it is better to put logic depends on spring beans in a dedicated class / bean.

Cheers
Mario