0

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.

Community
  • 1
  • 1
Dileep
  • 5,362
  • 3
  • 22
  • 38
  • 1
    Why does it have to be static? Make it non-static and move on. – duffymo Feb 18 '14 at 10:51
  • Its a logging mechanism which runs even before anyone logs in. Its linked with many functions like cron job etc.!! – Dileep Feb 18 '14 at 10:53
  • yes everything i am currently working on is for making it in a good shape. But Cant change it to a non static one its used in lots of places.!! Will consider your suggestion once we are done with the current modifications. – Dileep Feb 18 '14 at 10:57
  • @duffymo autowiring a static class is okie but its an interface ..!! That's why i am asking..!!Its not a duplicate... I itself provided a similar link in the Question. – Dileep Feb 18 '14 at 10:59
  • @duffymo Could you please explain how this becomes a duplicate..!! – Dileep Feb 18 '14 at 11:04
  • @Vitaly lol dude..!! I have linked the duplicate question in my own answer huh..!! Try to read the question fully before marking it as duplicate.Please click on the `this` in the last line of my post. – Dileep Feb 18 '14 at 11:24
  • @Dileep dude.. Did not you notice that the answer is the same? The same problem - the same solution with PostConstruct. – Vitaly Feb 18 '14 at 11:31
  • @Vitaly I am sorry i haven't seen the last Answer. The accepted answer was not a possible solution for an interface..!! – Dileep Feb 18 '14 at 11:37

2 Answers2

3

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.

Weibo Li
  • 3,565
  • 3
  • 24
  • 36
0

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

frenchfrie
  • 111
  • 6