Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing a Java library with Spring

Tags:

java

spring

I am extracting some functionality from an existing program into a separate library. This program uses Spring for dependency injection and other tasks and I'd like to keep using it in the library as well.

This library needs to monitor the filesystem for changes, so it will kick off some kind of separate thread to do this.

I don't really know what my options are for initialisation of the library:

  • How do I initialise the library's context? I cannot assume that library users will make use of Spring too, but I can distribute Spring with the library.

  • How do I manage my filesystem monitoring thread? Is it good design to expect the program to instantiate a main class of the library and the call init or something like that?

like image 614
Iker Jimenez Avatar asked Sep 08 '25 15:09

Iker Jimenez


1 Answers

How do I initialise the library's context? I cannot assume that library users will make use of Spring too, but I can distribute Spring with the library.

I am writing a library using Spring context as well and I did something like that, assuming your library is called FooLib, has two services called FooService and BarService and a class called SpringContext that configures your spring context through java config:

public final class FooLib {

    private static ApplicationContext applicationContext;

    private FooLib() {
    }

    public static FooService getFooService() {
        return getApplicationContext().getBean(FooService.class);
    }

    public static BarService getBarService() {
        return getApplicationContext().getBean(BarService.class);
    }

    private static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            applicationContext = new AnnotationConfigApplicationContext(SpringContext.class);
        }
        return applicationContext;
    }
}

Then a client can use BarService this way:

BarService barService = FooLib.getBarService();

How do I manage my filesystem monitoring thread? Is it good design to expect the program to instantiate a main class of the library and the call init or something like that?

You can start your monitoring subsystem statically within Spring context, inside the SpringContext class, for example.

@Configuration
@ComponentScan(basePackages = "com.yourgroupid.foolib")
public class SpringContext {

    @Bean
    public MonitoringSystem monitoringSystem() {
        MonitoringSystem monitoringSystem = new MonitoringSystem();
        monitoringSystem.start();
        return monitoringSystem;
    }

}

That should be enough because Spring creates its beans eagerly by default.

Cheers

like image 176
Marcio Oliveira Avatar answered Sep 10 '25 05:09

Marcio Oliveira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!