Access repository or service from entity
<p>I'm using Spring Boot to write server application.</p>

<p>Most of the time, I write all business logic inside services, where I use <code>@Autowired</code> to access repositories and other services.</p>

<p>However, sometimes I want to access certain service or property from <code>@Entity</code> class, which cannot use <code>@Autowired</code>. </p>

<p>For instance, I have an entity that should be able to serialize itself to JSON. In JSON, it should have imageUrl field, which contains of image name (stored in database and as a property in the <code>@Entity</code> class) and base url, which is only available in application.properties. This means that I have to use <code>@Value</code> annotation inside <code>@Entity</code> class, but it doesn't work that way.</p>

<p>So I create a service which looks like this:</p>

<pre><code>@Service
public class FilesService {

    private static FilesService instance;

    @PostConstruct
    public void init() {
        FilesService.instance = this;
    }

    public static FilesService getInstance() {
        return instance;
    }

    @Value("${files.path}")
    String filesPath;
    @Value("${files.url}")
    String filesUrl;

    public String saveFile(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return null;
        }
        String filename = UUID.randomUUID().toString();
        file.transferTo(new File(filesPath + filename));
        return filename;
    }

    public String getFileUrl(String filename) {
        if (filename == null || filename.length() == 0) {
            return null;
        }
        return filesUrl + filename;
    }

}
</code></pre>

<p>And then inside the <code>@Entity</code> class I write the following code:</p>

<pre><code>@JsonProperty
public String getImageUrl() {
    return FilesService.getInstance().getFileUrl(imageName);
}
</code></pre>

<p>This works, but it doesn't look right. Moreover, I concern whether this can lead to some side effects if used with less trivial <code>@Service</code> classes or <code>@Repository</code> classes.</p>

<p>What is the correct way to use <code>@Repository</code> and <code>@Service</code> classes from <code>@Entity</code> classes or any other non-<code>@Component</code> classes (classes not managed by Spring)?</p>