-
Notifications
You must be signed in to change notification settings - Fork 1
ProvidesMethods
Ruedi Steinmann edited this page Mar 25, 2015
·
3 revisions
When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method's return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
...
}
@Provides
TransactionLog provideTransactionLog() {
DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
transactionLog.setThreadPoolSize(30);
return transactionLog;
}
}If the @Provides method has a binding annotation like @PayPal or @Named("Checkout"), Salta binds the annotated type. Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method.
@Provides @PayPal
CreditCardProcessor providePayPalCreditCardProcessor(
@Named("PayPal API key") String apiKey) {
PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
processor.setApiKey(apiKey);
return processor;
}Salta wraps exceptions thrown by @Provides methods in a SaltaException. For checked exceptions, simply declare them as beeing thrown.
The Salta wiki. It was copied from the Guice Wiki and adapted to Salta.
- Home
- Why Dependency Injection?
- Getting Started
- Bindings
- Scopes
- Injections
- Injecting Providers
- AOP
- Speed
- Frequently Asked Questions
- Extending Salta
- Internals
- Best Practices
- Community