Spring: How to create a custom annotation to inject dependencies?

Viewed 161

What I want to achieve is having a class annotation which injects dependencies into the class. An example for that could be lombok's @Slf4j annotation. I add the annotation to the class and after that im able to call log.* from any place in my code.

I want to inject my feign client like that too. So I have a feign client for example:

@FeignClient("MY-CLIENT")
public interface MyClient {

  @PostMapping(value = "/api/v1")
  void get(@RequestBody MyModel model);
}

And I have some controller:

@RestController
@Slf4j
public class MyController {

}

I would like to be able to annotate that controller with some annotation so that it would work something like this:

@RestController
@Slf4j
@SomeCustomAnnotation
public class MyController {

    public void doSomething() {
        client.get(new MyModel())
    }

}

Is it possible to do something like that?

Ofcourse I could simply do this:

@RestController
@Slf4j
public class MyController {

    private final MyClient client;

    @Autowired
    public MyController(final MyClient client) {
        this.client = client;
    }

    public void doSomething() {
        client.get(new MyModel())
    }

}

But since I would need to do this in a ton of classes that seems to be way too much code for me.

0 Answers
Related