Spring Boot: accessing Autowired component in Runnable static Thread

AragornSG :

I need to access a @Component (TerminalLogHolder) in a separate thread, which is started in a static method. The component in the separate thread is not injected, so I started looking for solution and found separately, a way to access an @Autowired component in a static method and a way to inject the bean using applicationContext, however I was not able to make them work together.

Here is the code:

public class CommandExecutor {

    private static void printLog(Process process, String processLog) {
        ReadStream s1 = new ReadStream("stdin", process.getInputStream ());
        s1.start ();
    }

    public static class ReadStream implements Runnable {
        private String name;
        private String cmdId;
        private InputStream is;
        private Thread thread;

        @Autowired
        private TerminalLogHolder terminalLogHolder;

        public ReadStream(String name, InputStream is, String cmdId) {
            this.name = name;
            this.is = is;
            this.cmdId = cmdId;
        }

        public void start () {
            thread = new Thread (this);
            thread.start ();
        }

        public void saveLog(String s) {
            terminalLogHolder.addLog(cmdId, "[" + name + "] " + s);
        }

        public void run () {
            try {
                InputStreamReader isr = new InputStreamReader (is);
                BufferedReader br = new BufferedReader (isr);
                while (true) {
                    String s = br.readLine ();
                    if (s == null) break;
                    saveLog(s);
                }
                is.close ();
            } catch (Exception ex) {
                System.out.println ("Problem reading stream " + name + "... :" + ex);
                ex.printStackTrace ();
            }
        }
    }

}

I appreciate your help!

AragornSG :

As suggested by chrylis -on strike-, the solution was trivial constructor injection.

It was enough to pass to static method object Autowired elsewhere:

printLog(Process process, String processLog, TerminalLogHolder logHolder){
    ReadStream s1 = new ReadStream("stdin", process.getInputStream (), logHolder);
    s1.start ();
}

public static class ReadStream implements Runnable {
    private String name;
    private String cmdId;
    private InputStream is;
    private Thread thread;

    private TerminalLogHolder terminalLogHolder;

    public ReadStream(String name, InputStream is, String cmdId, TerminalLogHolder logHolder) {
        this.name = name;
        this.is = is;
        this.cmdId = cmdId;
        this.terminalLogHolder = logHolder;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418194&siteId=1