0

In a spring boot project I'm working on, we have a lot of classes that extend Consumer, Processor, or Producer custom abstract classes. All these concrete extension classes are also annotated with @Component, @ConditionalOnProperty and usually @Profile as well.

I just started learning about Java annotations and was wondering if it's possible (at all) to simplify my above scenario by creating custom @Consumer, @Processor, and @Producer annotations, such that doing

@Consumer(profile = "some_profile", conditionalOnName = "some_name", conditionalOnValue = "some_value")
public class MyCustomConsumer {
  // Abstract methods implementation
}

is the same as

@Component
@ConditionalOnProperty(name = "some_name", havingValue = "some_value")
@Profile("some_profile")
public class MyCustomConsumer extends Consumer {
  // Abstract methods implementation
}

and the missing abstract methods inherited from Consumer are enforced on MyCustomConsumer (meaning the compiler will complain that those methods are not implemented).

Seems like a very long shot in getting something like this to work (as my research into Java annotations hasn't shown any viable option), but seeing how Lombok can add code to my code without modifying the file, I thought I'd ask.

Is this possible?

gz90
  • 41
  • 7
  • how would that "simplify" anything? it takes less effort to add 'extends Consumer' compared to (correctly) configuring the right annotation – Stultuske Mar 03 '22 at 08:17
  • 1
    You can create so called _Meta Annotations_ to stack/combine annotations and then map fields with aliases. However, as @Stultuske mentioned, it will take way more effort to implement an _annotation processor_ to generate code for you like Lombok does. – Nick Mar 03 '22 at 08:18
  • @Stultuske It would simplify things in that it would reduce the boilerplate code we keep repeating on all these concrete classes -- going on 40+ implementations combined so far... quite a monolith, I know, but it fits our use case as only a small subset of components is initialized through configuration – gz90 Mar 09 '22 at 23:11
  • @Ortix92 thanks for the pointers... I was doing very general searches and but now I can narrow it down knowing the technical words (and better understand the level or effort) – gz90 Mar 09 '22 at 23:11
  • @gz90 exchanging one repeated part of code with a slightly larger part of repeated code is not reducing boilerplate code, it's adding to it. Not to mention the effort you'll have to put in implementing the actual functionality behind the annotation, while Java already provides that for you ... – Stultuske Mar 10 '22 at 07:15

0 Answers0