Is there a way to prevent the use of the spring bean class?

Is there a way (any base class annotation) that I can mark the class in such a way that spring throws an error when initializing the context? Basically I have a class that is not thread safe by design and I dont want anyone to use it with spring as a singleton bean. I know it can be used as a prototype bean, but I can disable it, is it used as a spring bean at all?

+3


source to share


3 answers


Make a post-initialisation throw method.

Or do InitializingBean

public final void afterPropertiesSet() {
    throw new UnsupportedOperationException();
}

      



Or use JEE annotation

@PostConstruct
public final void forbidDependencyInjection() {
    throw new UnsupportedOperationException();
}

      

+6


source


You can use your own BeanPostProcessor



public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { 
   Class<?> targetClass = AopUtils.getTargetClass(bean);
   if (targetClass == MyProhibited.class)) {
       ....
       return null;
    }

   return bean;
}

      

+2


source


You can define an aspect around or in front of all or some of the methods of this class that will throw an exception if called. This does not require any modification to the class.

+1


source







All Articles