How to inject objects of the same class with different scopes?

纵然是瞬间 提交于 2019-12-02 09:50:31

The reason for the inclusion of this recommendation is the same reason one would prefer Enumeration over arbitrary strings for constants and that is because its not type-safe. You can easily mistype the name of the class and it would compile fine and fail at runtime. The recommendation is included because in most cases @named makes your application unnecessarily fragile when you have the ability force these constraints at compile time.

Here is a good article that outlines the reasons:

The preferred way to handle this situation is using @Qualifiers with enumerated values. Checkout the section entitled "String Qualifiers are Legacy" and "The Right Way" for the steps to handle this.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!