带有条件注释的原型范围



我尝试在每个请求上重新加载bean。

在我的控制器中,我每次从applicationContext:

@Controller
public class LabelsController implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    @RequestMapping("/...")
    public ModelAndView labelConcerns()  {
        System.out.println("Here I ask for a fresh bean");
        InconsistentCaseDetector inconsistentCaseDetector = applicationContext.getBean(InconsistentCaseDetector.class);

InconsistentCastedEtector是一个原始接口。我有几个实现的注释,如下所示(不同的条件):

@Component
@Conditional(SkosFormatSelected.class)
@Scope(value = "prototype", proxyMode = ScopedProxyMode.INTERFACES)
public class InconsistentCaseDetectorImpl implements InconsistentCaseDetector {
...

条件的一个例子:

public class SkosFormatSelected implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        System.out.println("Is skos format selected ?");
        return Formats.getCurrent().equals(Formats.SKOS);
    }

但是,条件类的matches方法仅在启动时被调用。在启动期间,日志指令("选择SKOS格式?

org.springframework.context.annotation.ClassPathBeanDefinitionScanner  - Identified candidate component class: file [/home/..../.../WEB-INF/classes/tests/model/vocabulary/skos/algorithm/InconsistentCaseDetectorImpl.class] 

,但随后在每个请求下,条件不再执行,它始终与所服务的实现相同。这是日志在运行时显示的内容:

Here I ask for a fresh bean
163326 [http-nio-8080-exec-23] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Returning cached instance of singleton bean 'inconsistentCaseDetectorImpl'
...
163328 [http-nio-8080-exec-23] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'scopedTarget.inconsistentCaseDetectorImpl'
163329 [http-nio-8080-exec-23] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Finished creating instance of bean 'scopedTarget.inconsistentCaseDetectorImpl'

因此,当我请求BEAN时,它会从缓存中返回一个实例,而不是创建新的实例。后来,但是我不知道在哪里,它似乎创建了一个新的,但仍不执行条件条款。

使用

@Autowired
@RequestMapping("/...")
public ModelAndView labelConcerns(final InconsistentCaseDetector inconsistentCaseDetector)  {
    ...
}

应该工作。

顺便说一句,

  1. 您应该将@Component移至接口(干/SRP),也许也是@Scope
  2. 您应该注入ApplicationContext,而不是使用接口ApplicationContextAware(DIP)

最新更新