java - 使用 javax 注解在 spring 中创建 session 作用域 bean

标签 java spring javax-inject

我正在使用带有 javax 注释 (JSR-330) 的 spring 4。在行家

     <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

所以我使用@Named , @Inject@Resource来自 javax.annotation.*来自 javax.inject.*而不是 Spring @Autowire , @Component , ... 并且 spring 很好地支持它们。很好的例子:http://www.mkyong.com/spring3/spring-3-and-jsr-330-inject-and-named-example/

我的问题是我不能在带有 javax 注释的 session 范围内拥有一个 bean,所以我使用了 @Named和 Spring @Scope : org.springframework.context.annotation.Scope

我可以使用 javax 注释创建 session 作用域 bean 吗?!

最佳答案

As per this blog and the Official specification, JSR 330 does not support scopes like request or session out of the box. You will have to create your own annotations for this.

让我们看一下,如何针对请求范围执行此操作。

创建您自己的范围注释:

@Scope
@Documented
@Retention(RUNTIME)
public @interface Request {
}

扩展 Jsr330ScopeMetadataResolver 以将您的注释映射到 Spring 的范围:

public class CustomScopeMetadataResolver extends Jsr330ScopeMetadataResolver {

  public Jsr330SpringScopeMetadataResolver() {
    registerScope(Request.class.getName(), WebApplicationContext.SCOPE_REQUEST);
  }

}

在 Spring 配置中使用自定义解析器:

<context:component-scan base-package="my.package"
  scope-resolver="my.resolver.package.CustomScopeMetadataResolver" />

引用信用:Spring and JSR 330 scopes

关于java - 使用 javax 注解在 spring 中创建 session 作用域 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895984/

相关文章:

java - 如何修复 ApplicationResources_fr.properties 损坏

java - WebSocket 握手 - 意外的响应代码 200 - AngularJs 和 Spring Boot

Java注释和方法一致性

java - ServerBootstrap绑定(bind)方法

java - 如何将 Map<String, String> 转换为 RequestBody?

用于检测的Java源代码属性计数

java - Hibernate 和 Spring 事务管理器 : Transaction Not Successfully Started