注射@Resource

Spring 还支持使用 JSR-250 进行注入@Resource注解 (jakarta.annotation.Resource) 在字段或 bean 属性 setter 方法上。 这是 Jakarta EE 中的一种常见模式:例如,在 JSF 管理的 Bean 和 JAX-WS 中 端点。Spring 也支持 Spring 管理的对象的这种模式。spring-doc.cadn.net.cn

@Resource采用 name 属性。默认情况下,Spring 将该值解释为 要注入的 Bean 名称。换句话说,它遵循按名称语义, 如以下示例所示:spring-doc.cadn.net.cn

public class SimpleMovieLister {

	private MovieFinder movieFinder;

	@Resource(name="myMovieFinder") (1)
	public void setMovieFinder(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}
}
1 此行注入@Resource.
class SimpleMovieLister {

	@Resource(name="myMovieFinder") (1)
	private lateinit var movieFinder:MovieFinder
}
1 此行注入@Resource.

如果未显式指定名称,则默认名称派生自字段名称或 setter 方法。如果是字段,则采用字段名称。在 setter 方法的情况下, 它采用 bean 属性名称。以下示例将有 bean 叫movieFinder注入到其 setter 方法中:spring-doc.cadn.net.cn

public class SimpleMovieLister {

	private MovieFinder movieFinder;

	@Resource
	public void setMovieFinder(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}
}
class SimpleMovieLister {

	@set:Resource
	private lateinit var movieFinder: MovieFinder

}
注释提供的名称由ApplicationContext其中CommonAnnotationBeanPostProcessor是知道的。 如果将 Spring 的SimpleJndiBeanFactory明确地。但是,我们建议您依赖默认行为和 使用 Spring 的 JNDI 查找功能来保留间接级别。

在排他性情况下@Resource未指定显式名称的用法,以及类似的用法 自@Autowired,@Resource查找主类型匹配项,而不是特定的命名 Bean 并解析众所周知的可解析依赖项:该BeanFactory,ApplicationContext,ResourceLoader,ApplicationEventPublisherMessageSource接口。spring-doc.cadn.net.cn

因此,在以下示例中,customerPreferenceDao字段首先查找 bean 命名为“customerPreferenceDao”,然后回退到该类型的主类型匹配CustomerPreferenceDao:spring-doc.cadn.net.cn

public class MovieRecommender {

	@Resource
	private CustomerPreferenceDao customerPreferenceDao;

	@Resource
	private ApplicationContext context; (1)

	public MovieRecommender() {
	}

	// ...
}
1 context字段根据已知的可解析依赖项类型注入:ApplicationContext.
class MovieRecommender {

	@Resource
	private lateinit var customerPreferenceDao: CustomerPreferenceDao


	@Resource
	private lateinit var context: ApplicationContext (1)

	// ...
}
1 context字段根据已知的可解析依赖项类型注入:ApplicationContext.