0

I want to implement FusionAuth in a microservices enviroment with spring boot, so i want to make a singleton of the FusionAuth Client for java. But i get error for using the variables apiKey, baseUrl in a static context.

@Configuration
public class FusionAuthClientConfig {

    private static FusionAuthClient INSTANCE = null;

    @Value("${fusionAuth.apiKey}")
    private String apiKey;

    @Value("${fusionAuth.baseUrl}")
    private String baseUrl;

    public static FusionAuthClient getInstance() {
        if(INSTANCE == null)
            INSTANCE = new FusionAuthClient(apiKey, baseUrl);

        return INSTANCE;
    }
}

Anyway, is this scope of singleton class used? I mean for concurrency enviroments and performance, should i use a client for each request to fusion auth?

1 Answers1

0

Your private static FusionAuthClient INSTANCE = null is unnecessary. By default, beans are scoped as singletons. @see: Bean Scopes

Since you're using @Configuration, all you need to do is change your FusionAuthClientConfigto the following and you will be able to reference it elsewhere in your application as an @Autowired property.

@Configuration
public class FusionAuthClientConfig {

    @Value("${fusionAuth.apiKey}")
    private String apiKey;

    @Value("${fusionAuth.baseUrl}")
    private String baseUrl;

    @Bean
    public FusionAuthClient fusionAuthClient() {
        return new FusionAuthClient(apiKey, baseUrl);
    }
}

Now your fusionAuthClient bean can be referenced elsewhere like this:

@Service
//or @Component etc
public class MyService {
    private final FusionAuthClient fusionAuthClient;

    public MyService(FusionAuthClient fusionAuthClient) {
        this.fusionAuthClient = fusionAuthClient;
    }

    public void doTheThing() {
        // use this.fusionAuthClient
    }
}
Chris Moran
  • 398
  • 2
  • 12