1

I am using the below code to get all the beans in the application.

Map<String, MyBuilder> allBuilders = context.getBeansOfType(MyBuilder.class);

After getting each beans, how do I get the class to which that particular bean is avalibale?

For example, considering the below code:

@MyAnnotation(name = "one")
public class MyService{

    @Dummy(description = "test")
    public MyBuilder builder1() {
        return someValue;
    }
}

Using getBeansOfType() method gives the "builder1" bean of type "getBeansOfType". But how do I get the actual super class in which this bean is available?

For the provided example, I want the class MyService and it's annotations to be the output.

Ideally, I want to get all the below information from the above code.

  1. MyAnnotation Parameter (name = "one") from MyService class
  2. Dummy Parameter ( description = "test")
  3. MyBuilder bean object
Purus
  • 5,701
  • 9
  • 50
  • 89
  • It is not really clear, what you mean by "parent class". It seems, you do not mean the actual parent class of the bean (in terms of Java) but rather the class where the method is located which the bean was created by? Or the configuration class where the bean's factory method is located? – DanielBK Feb 03 '20 at 12:07
  • @DanielBK Updated the question. I want to get the class where the bean is actual located. – Purus Feb 03 '20 at 12:08
  • maybe this helps: https://stackoverflow.com/questions/21435522/spring-bean-definition-get-bean-class – Shafiul Feb 03 '20 at 14:38
  • @Shafiul The accepted answer is very old and sure there must be updated solution by now. The other answer looks incomplete. – Purus Feb 03 '20 at 16:48

1 Answers1

0

You can't assume your myservice bean will actually be a class of MyService. If you want a 100% sure method to do this is to store the class in a variable:

@MyAnnotation(name = "one")
public class MyService{

    Class<MyService> clss = MyService.class;

    @Dummy(description = "test")
    public MyBuilder builder1() {
        return someValue;
    }
}

Then you have access to the class and can use reflection to read the annotations as you normally would.

This isn't the nicest solution and I think normally you would rely on extending Springs annotations or using AspectJ, than interpreting Annotations manually.

Derrops
  • 7,651
  • 5
  • 30
  • 60