Joe Attardi
Joe Attardi

Reputation: 4521

Long-running service in Spring?

I want to have a service in my Spring application that watches a directory for changes using the Java 7 WatchService. The idea is that when a file in the directory is changed, clients connected via WebSockets are notified.

How do I get a bean to run in its own thread as a service?

Upvotes: 2

Views: 4035

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280000

What you are looking for is Asynchronous execution. With a correctly configured context (see the link), you declare a class like so

@Component
public class AsyncWatchServiceExecutor {
    @Autowired
    private WatchService watchService; // or create a new one here instead of injecting one

    @Async
    public void someAsyncMethod() {
        for (;;) {
            // use WatchService
        }
    }
}

Everything you do in someAsyncMethod() will happen in a separate thread. All you have to do is call it once.

ApplicationContext context = ...; // get ApplicationContext
context.getBean(AsyncWatchServiceExecutor.class).someAsyncMethod();

Use the WatchService as described in the Oracle documentation.


If you don't have direct access to your ApplicationContext, you can inject the bean in some other bean and call it in a @PostConstruct method.

@Component
public class AsyncInitializer {
    @Autowired
    private AsyncWatchServiceExecutor exec;

    @PostConstruct
    public void init() {
        exec.someAsyncMethod();
    }
}

Careful which proxying strategy (JDK or CGLIB) you use.

Upvotes: 5

Related Questions