如何使用不同的范围注入相同类的对象

如何使用不同的范围注入相同类的对象

本文介绍了如何使用不同的范围注入相同类的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在简单性和正确性方面,注入具有不同范围的同一类对象的最佳方法是什么?

servlet我想要注入具有不同范围的同一类的对象。
仍然不知道是否要使用jsf。

In a servlet I want to have injected objects of the same class with different scopes.Still don't know if going to use jsf.


  • 简单:制作限定符并且每个范围的生产者方法太多了;在 beans.xml 中创建一个接口,两个类以及添加和替换也是太多了;拥有地址#isCurrent()方法没有意义。

  • 正确性:JSR299,3.11说:使用不建议使用@Named作为注射点限定符。仍然不知道原因。
    尽管在注射时使用 @Named point适用于 @ApplicationScoped
    @RequestScoped 但不适用于 @SessionScoped 。请参阅下面的命名代码段

  • Simplicity: Making a Qualifier and a producer method for each scope is too much; making an interface, two classes and adding and alternative in beans.xml is also too much; having an Address#isCurrent() method doesn't make sense.
  • Correctness: JSR299, 3.11 says: The use of @Named as an injection point qualifier is not recommended. Still don't know why.
    Though using @Named at injection point works with @ApplicationScoped and@RequestScoped but not with @SessionScoped. See named snippet below.

春天很容易:

Spring片段

<bean id="currentAddress" class="xxx.Address" scope="session" />
<bean id="newAddress" class="xxx.Address" scope="request" />
<bean id="servlet" class="xxx.MyServlet">
 <property name="currentAddress" ref="currentAddress" />
 <property name="newAddress" ref="newAddress" />
</bean>


命名代码段

/* Address class */
@Produces @RequestScoped @Named(value="request")
 public Address getNewAddress(){
 return new Address();
}

@Produces @SessionScoped @Named(value="application")
 public Address getCurrentAddress(){
 return new Address();
}
/* Servlet */
@Inject @RequestScoped @Named("request")  private Address newAddress;
@Inject @ApplicationScoped @Named("application") private Address currentAddress;


推荐答案

感谢@ nsfyn55指出,阅读正确的方法一节我想出了我认为在简单性和正确性方面实现它的最佳方法。

Thanks to @nsfyn55 for pointing out that good article, after reading the section "The Right Way", I came up with what I think is the best way to achieve it in terms of simplicity and correctness.

所以我只使用一个接口进行限定符注释。

So I am using only one interface for the qualifier annotation.

/* Qualifier annotation */
@Qualifier
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface Scope {

 Type value();

 enum Type { REQUEST, SESSION, APPLICATION };
}


/* Address class */
@Produces @Scope(REQUEST) @RequestScoped
 public Address request() {
 return new Address();
}

@Produces @Scope(SESSION) @SessionScoped
 public Address session() {
 return new Address();
}

/* Servlet */
@Inject @Scope(REQUEST)
private Address newAddress;

@Inject @Scope(SESSION)
private Address currentAddress;

这篇关于如何使用不同的范围注入相同类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:34