I have a case where by I want all the classes that implement a particular interface to also inherit the annotations of the class, as well as the methods.
@Component
public interface ITask {
@Scheduled(fixedRate = 5000)
void execute();
}
public class TaskOne implements ITask {
private static Logger LOGGER = LoggerFactory.getLogger(TaskOne.class);
@Override
public void execute() {
LOGGER.info("Hello from task one");
}
}
public class TaskTwo implements ITask {
private static Logger LOGGER = LoggerFactory.getLogger(TaskTwo.class);
@Override
public void execute() {
LOGGER.info("Hello from task two");
}
}
So, I wanted both the tasks to be treated as a bean, as they are implementing an interface that is a bean. Also, I was hoping that the execute()
methods of both the tasks would be scheduled at every 5 seconds. I have used the annotation @EnableScheduling with the main Application class containing the main()
method.
Instead, I have to do this to make it execute in a periodic manner :
public interface ITask {
void execute();
}
@Component
public class TaskOne implements ITask {
private static Logger LOGGER = LoggerFactory.getLogger(TaskOne.class);
@Override
@Scheduled(fixedRate = 5000)
public void execute() {
LOGGER.info("Hello from task one");
}
}
@Component
public class TaskTwo implements ITask {
private static Logger LOGGER = LoggerFactory.getLogger(TaskTwo.class);
@Override
@Scheduled(fixedRate = 5000)
public void execute() {
LOGGER.info("Hello from task two");
}
}
I don't want want to annotatae every task with this @Component
annotation, and the @Scheduled
annotation for every execute method. I was hoping to provide some default value for @Scheduled
, and that the @Component
annotation can be taken care of by implementing a certain interface.
Is it possible in Java ?