2

我看到 JSR-330 @Inject 注释没有将 ApplicationContext 填充到我的 bean 中的问题。使用 JSR-250 @Resource 注释时,它会被正确注入。是的,我知道我可以让 MyClass 实现 ApplicationContextAware,但想知道为什么 @Resource 可以工作,但 @Inject 不能。我正在使用 spring-context 版本 4.1.6.RELEASE 和 java 8

这有效:

@Named
public class MyClass {

  @Resource
  public ApplicationContext applicationContext;

...
}

这有 ApplicationContext 为空

@Named
public class MyClass {

  @Inject
  public ApplicationContext applicationContext;

  ...
}
4

1 回答 1

1

There was/is a lot of confusion, as JSR-330 (Dependency Injection for Java) led by Rod Johnson (SpringSource) and Bob Lee (Google Inc.) became a part of Java EE 6. JSR-330 is very simplistic. It comes with own few annotations from the package: javax.inject. The package contains the following elements: Inject, Qualifier, Scope, Singleton, Named and Provider. Its the definition of the basic dependency injection semantics.

JSR-299 (Java Contexts and Dependency Injection), with Gavin King as lead, uses JSR-330 as base and enhances it significantly with modularization, cross cutting aspects (decorators, interceptors), custom scopes, or type safe injection capabilities. JSR-299 is layered on top of JSR-330.

It is amusing to see that the built-in qualifier @Named is not recommended and should be used only for integration with legacy code:

"The use of @Named as an injection point qualifier is not recommended, except in the case of integration with legacy code that uses string-based names to identify beans." [3.11 The qualifier @Named at injection points, JSR-299 Spec, Page 32]

source http://www.adam-bien.com/roller/abien/entry/what_is_the_relation_between

于 2017-09-26T15:22:55.193 回答