I want to implement DI in my application, but after I did this I have issues with CRUD methods.
I've created interface:
@Singleton
@Component(modules = {AppModule.class, DbModule.class, AuthGatewayModule.class})
public interface AppComponent {
Context getContext();
GymService getGymService();
KitchenService getKitchenService();
ActivitiesService getActivitiesService();
AuthGateway getAuthGateway();
LandingService getLandingService();
Logger getLogger();
void inject(Logger logger);
}
This is appModule:
@Module
public class AppModule {
private final Context context;
public AppModule(Context context) {
this.context = context;
}
@Provides
@Singleton
public Context provideContext() {
return context;
}
@Provides
@Singleton
public Logger logger() {
return new Logger(context);
}
}
And dbModule:
@Module
public class DbModule {
@Provides
public DbService provideDbService(Logger logger) {
return new DatabaseController(Regions.EU_CENTRAL_1, logger);
}
}
This is my KitchenService class with one example method:
public class KitchenService {
private DatabaseController databaseController;
private LambdaLogger logger;
@Inject
public KitchenService(){}
public KitchenService(DatabaseController databaseController, LambdaLogger logger) {
this.databaseController = databaseController;
this.logger = logger;
}
//PRODUCT CRUD METHODS
public Product addProduct(Product product) {
databaseController.save(product);
logger.log("Product created");
return product;
}
I wanted to add some product to DB, that worked fine before I implemented DI, but now I have java.lang.NullPointerException.
And this is AddProductLambda class:
public class AddProductLambda extends Lambda {
@Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
super.handleRequest(input, context);
try {
Product product = RequestUtil.parseRequestBody(input, Product.class);
KitchenService kitchenService = appComponent.getKitchenService();
Product addedProduct = kitchenService.addProduct(product);
return ResponseUtil.generateResponse(HttpStatus.SC_CREATED, addedProduct);
} catch (IllegalArgumentException e) {
return ResponseUtil.generateResponse(HttpStatus.SC_BAD_REQUEST, e.getMessage());
}
}
}
And Lambda that AddProductLambda extends:
public abstract class Lambda implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
protected Logger logger;
protected AppComponent appComponent;
@Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
appComponent = DaggerAppComponent.builder().appModule(new AppModule(context)).build();
logger = new Logger(context);
// Inject logger
appComponent.inject(logger);
logger.log(input.toString());
return null;
}
}
I did something wrong? Can someone help me with this problem?