Custom annotations

If you have shared dependencies, that you want to easily access throughout your entire applications, you might want to consider using custom annotations, so you do not need to specify @Inject(...long properties) every time.

@Service
class MyLogger {
    @Override
    public void log(String message) {
        System.out.println("LOG: " + message);
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Logger {
}

void initLogger() {
    Container.registerProvider(
        Logger.class, 
        (target, annotation, container) -> new MyLogger()
    );
}

@Service
class UserController {
    @Logger
    MyLogger logger;

    public void init() {
        logger.log("UserController has been initialized!");
    }
}

Last updated