Debsankar Mukhopadhyay
Debsankar Mukhopadhyay

Reputation: 133

javax.inject.Provider vs String

I am trying to retrieve a set of JNDI keys in a webapp during the runtime. The code looks like:

class Test{
    private final String someUrl;

    public Test(@Named("URL") String someUrl){
    // do something
    }

     public void dotEST( string someUrl){
      String x = someUrl;
      //some other logic
     }

}

I want to understand the difference between using the above code and this:

class Test{
    private final Provider<String> someUrl;

    public Test(@Named("URL") Provider<String> someUrl){
    // do something
    }

     public void dotEST( Provider<String> someUrl){
      String x = someUrl.get();
      //some other logic
     }    
}

When and why should I use provider?

Upvotes: 1

Views: 811

Answers (2)

Johan Tid&#233;n
Johan Tid&#233;n

Reputation: 695

I would use a provider if the value is complex or expensive to calculate. Maybe you would Provide a connection to the database, or fetching of some remote configuration values.

KISS - Keep it simple, stupid, is key when working with injection frameworks. The more you can rely on simple things (like types), the better. It can quickly grow into a mess that is hard to get out of.

Even @Named(...) is complex, so I would avoid that too if possible. It will probably be easier (not simpler??) long term to have a placeholder class for that string value.

class UrlToTheServer {
    private final String url;
}

...

class Test{
    private final String someUrl;

    @Inject
    public Test(UrlToTheServer urlToTheServer){
        someUrl = urlToTheServer.url;
    }

    public void foo() {
       // access someUrl here.
    }
 }

}

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32507

 public Test(@Named("URL") String someUrl){

To call this method, someUrl must already be resolved and available (eg to the container)

public Test(@Named("URL") Provider<String> someUrl){

here, retrieval can be postponed (or even not done) - its similar to lazy initialization. It dependes on implementation of Provider interface.

Upvotes: 1

Related Questions