OTUser
OTUser

Reputation: 3848

How to Dynamically create Spring bean and Set Annotations on the newly created bean

Am trying to to dynamically create Spring bean and Set Annotations on the newly created bean to unit test the below piece of code

class BeanMetadata 
{
    int id;
    String type;
    String beanName;
    Date createdAt;
    Date createdBy;
}

This method gets the bean name from BeanMetadata and searches in the applicationCOntext for the given bean and checks if the bean has @OperationExecutePermission or @AdministerPermission annotations present on the bean.

So am trying to to dynamically create Spring bean and Set these annotations on the newly created

void addCommandPermissions(BeanMetadata command) {
    if (applicationContext.containsBean(command.getBeanName())) {
            Object bean = applicationContext.getBean(command.getBeanName());
            Class<?> beanClass = bean.getClass();
            if (beanClass.isAnnotationPresent(AdministerPermission.class)) {
                overrideAdminPermission =   beanClass.getAnnotation(AdministerPermission.class).name();
            }
            if (beanClass.isAnnotationPresent(OperationExecutePermission.class)) {
                overrideExecPermission =    beanClass.getAnnotation(OperationExecutePermission.class).name();
            }
        }

I am trying to achieve if (beanClass.isAnnotationPresent(AdministerPermission.class)) must be true or if (beanClass.isAnnotationPresent(OperationExecutePermission.class)) must be true for the newly created bean.

Upvotes: 0

Views: 1392

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280141

You cannot add annotations to anything at runtime.

The best you can do here is create a class that has the annotations. You can then test your code with classes that have the annotations and classes that don't.

Upvotes: 1

Related Questions