Question

How can i Autowire a static interface class

This is my Code

@Autowired
private static IAuditLogRepository iAuditLogRepository;

public static int saveLog(LogFile logFile){
iAuditLogRepository.saveLog(logFile);  // Autowireing fails and iAuditLogRepository is null.
}

My interface class

public interface IAuditLogRepository {
    public Serializable saveLog(LogFile logFile);
}

How can i Autowire the interface.?

I have looked into this. How can i do the same for an interface class.

Was it helpful?

Solution

You can't @Autowired a static field. But there is a tricky skill to deal with this:

public class Foo {

private static IAuditLogRepository iAuditLogRepository;

@Autowired
private IAuditLogRepository iaRepos;

@PostConstruct
public void someFunction () {
iAuditLogRepository = iaRepos;
}


public static int saveLog(LogFile logFile){
iAuditLogRepository.saveLog(logFile); 
}


}

In one word, @Autowired a instance field, and assign the value to the static filed when your object is constructed.

OTHER TIPS

As I'm not allowed comments, I will post answer: Use a singleton instead of static methods here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top