Spring: How to pass configuration from application to library

Isonlaxman :

I am building a Spring package that any Spring Application can use to perform session management (much like express-session in NodeJS). This library needs to take in the application's JPA configuration (such as url of database, username, password, and other additional datasource properties, again just like express-session), along with some other library-specific properties. I also want the application to be able to pass a function to the library, which the library can then call to generate a token, if the application wishes to use its own token generation function.

I've looked into @Imports, however, I think that requies the to-be-imported class to be in the same package, which would not be the case since the application would an entirely different package than the library. Is there a way to search for the application configuration class using just its name?

I know I can ask the application to make an application.properties file and then use @EnableAutoConfiguration to pass those values along, but this fails when I also want to pass a function. I guess a way around that is to pass a function name and call that using reflection? Although I'm not sure how that would work and I do not wish to do that.

Here is my config class which should be able to take in application's config

@Configuration
public class SuperTokensAppConfig {

    @Bean
    public DataSource dataSource() {
        // use the application's datasource here and return it
    }

Here is the interface which would have all the necessary library-specific properties and functions. Application should be able to extend this, and I should be able to Autowire that bean using the name of this interface (see below)

public interface SuperTokensAccessKeyConfig {
    public String userFunction();
    public boolean dynamic;
    ... 
}

Here is the Service that would use the user generated function

@Service
public class AccessTokenKey {
    ...
    @Autowired
    private SuperTokensAccessKeyConfig userConfig = null; // this would have the function I need

    private String useUserFunction() {
        return userConfig.userFunction();
    }
}
Ramin Manesh :

introduce the package of configuration, service, repo ... from your library via

@ComponentScan({"com.my.package.first","com.library.session.management.config"})

in your main application.

The better solution is however to create your own auto configuration: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161865&siteId=1