문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top