Skip to content

Instantly share code, notes, and snippets.

@asouza
Created September 16, 2015 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asouza/1200a7c8ac07bfeeb4b0 to your computer and use it in GitHub Desktop.
Save asouza/1200a7c8ac07bfeeb4b0 to your computer and use it in GitHub Desktop.
Processor that converts all controllers in request scoped objects :). Just an example.
package br.com.casadocodigo.loja.infra.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
@Configuration
public class ControllersMustBeRequestScope implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory factory) throws BeansException {
for (String beanName : factory.getBeanDefinitionNames()) {
BeanDefinition beanDef = factory.getBeanDefinition(beanName);
if(beanDef instanceof AnnotatedBeanDefinition){
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDef;
AnnotationMetadata metadata = annotatedBeanDefinition.getMetadata();
if(metadata.hasAnnotation(Controller.class.getName())){
beanDef.setScope(WebApplicationContext.SCOPE_REQUEST);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment