Home > Software engineering >  Spring-Boot: Create instances of custom annoated classes
Spring-Boot: Create instances of custom annoated classes

Time:10-22

For a project, I'm trying to collect all the classes for a specific custom annotation and create it's instances. Or use Spring-Boot instances created in it's context.

Here is the custom annotation:

public @interface MyAnnotation {
   String name();
}

Here are the classes using this annotation in various packages:

In com.my.project.package1

@MyAnnotation(name = "package_1_impl")
public class Package1Impl {}

In com.my.project.package2

@MyAnnotation(name = "package_2_impl")
public class Package2mpl {}

Now, I would like collect all these implementation instances and use them for strategy pattern for example.

So, I want to do something like the following. The following is just my assumption that such a thing exists.

Option#1 In my Service class: MyAnnotationService.java:

@Service
@Singleton
class MyAnnotationService {
   
     public MyAnnotationService() {
         List<String> classNamesToLoad = SpringSomething.findWithAnnotation(MyAnnotation.class);
         
         for (String cls : classNamesToLoad) {
           createNewInstance(cls);
         }
 
     }
}

Option#2 In my Service class: MyAnnotationService.java:

@Service
@Singleton
class MyAnnotationService {
   
     public MyAnnotationService() {
         Map<String, Object> objectsCreatedBySpring = SpringSomething.findWithAnnotation(MyAnnotation.class);
     }
}

I'm not sure where and what to look for to achieve this. Or if it's even possible.

CodePudding user response:

There is a solution for this.

Add the @Component annotation so your classes are managed by Spring. Then from the ApplicationContext, you can get all the beans and even specific beans from an annotation with getBeansWithAnnotation.

Example

Map<String,Object> beans = applicationContext.getBeansWithAnnotation(Foo.class);
  • Related