spring - 自定义 Spring 范围中的 resolveContextualObject 和 getConversationId

标签 spring

我想知道 org.springframework.beans.factory.config.Scope.resolveContextualObject(String key) 的目的是什么和 org.springframework.beans.factory.config.Scope.getConversationId() ?

来自 javadoc :

Object resolveContextualObject(String key)

Resolve the contextual object for the given key, if any. E.g. the HttpServletRequest object for key "request".

String getConversationId()

Return the conversation ID for the current underlying scope, if any. The exact meaning of the conversation ID depends on the underlying storage mechanism. In the case of session-scoped objects, the conversation ID would typically be equal to (or derived from) the session ID; in the case of a custom conversation that sits within the overall session, the specific ID for the current conversation would be appropriate.



这个描述并没有告诉我太多。
你能给我一些例子来演示如何使用这些方法吗?

我的观察是resolveContextualObject(String key)看起来像代码异味,其中 Scope 可以暴露一些内部对象。

最佳答案

拥有:

public class MyCustomScope implements Scope {

    private Pair<String, String> myPair;

    @Override
    public Object resolveContextualObject(String key) {
        if ("myKey".equals(key)) return myPair;
        return null;
    }

    // ...
}

@Configuration
public class RegisterMyScopeConfig {

    @Bean
    public BeanFactoryPostProcessor beanFactoryPostProcessor() {
        return beanFactory -> beanFactory.registerScope(
            "mycustomscope", new MyCustomScope()); 
    }
}

然后你可以:
@Scope("mycustomscope")
@Component 
class MyComponent {

    @Value("#{myKey.first}")
    private String firstOfMyPair;

    // or 

    @Value("#{myKey}")
    private Pair<String,String> myPair;
}

当然,您如何解析与键匹配的对象的方式可能更有趣;)。
例如,在 GenericScope它看起来像这样:
@Override
public Object resolveContextualObject(String key) {
    Expression expression = parseExpression(key);
    return expression.getValue(this.evaluationContext, this.beanFactory);
}

关于spring - 自定义 Spring 范围中的 resolveContextualObject 和 getConversationId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42186665/

相关文章:

java - Spring配置服务器找不到纯文本文件

java - 通过组合 @Scheduled 和 @Configurable 减慢速度

java - Camel .beanRef 已弃用 - 现在如何在 Java DSL 路由中访问容器管理的 bean?

java - Appengine 标准上的 Spring Boot

java - 如何使用spring + hibernate向数据库中插入数据?

Spring MVC @RestController 和重定向

java - Hibernate onetomany 中的外键未更新

spring - Camel : Jetty response encoding

spring - 覆盖 spring @ExceptionHandler 方法

java - 如何检查@Async调用在Spring中完成?