我正在使用带有 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 likerequest
orsession
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" />
关于java - 使用 javax 注解在 spring 中创建 session 作用域 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895984/