注射用@Resource
Spring 还支持使用 JSR-250 进行注入@Resource
注解
(jakarta.annotation.Resource
) 或 Bean 属性 setter 方法。
这是 Jakarta EE 中的一种常见模式:例如,在 JSF 托管的 bean 和 JAX-WS 中
端点。Spring 也支持 Spring Management 的对象使用这种模式。
@Resource
接受 name 属性。默认情况下,Spring 将该值解释为
要注入的 bean 名称。换句话说,它遵循 by-name 语义,
如以下示例所示:
-
Java
-
Kotlin
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 属性 name。以下示例将具有 bean
叫movieFinder
注入到其 setter 方法中:
-
Java
-
Kotlin
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Resource
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
class SimpleMovieLister {
@set:Resource
private lateinit var movieFinder: MovieFinder
}
随 Comments 提供的名称由ApplicationContext 其中,CommonAnnotationBeanPostProcessor 是有意识的。
如果您配置 Spring 的SimpleJndiBeanFactory 明确地。但是,我们建议您依赖默认行为和
使用 Spring 的 JNDI 查找功能来保持间接级别。 |
在 exclusive case 中@Resource
未指定显式名称的用法,以及类似的
自@Autowired
,@Resource
查找主要类型匹配项,而不是特定的命名 Bean
并解析众所周知的可解析依赖项:BeanFactory
,ApplicationContext
,ResourceLoader
,ApplicationEventPublisher
和MessageSource
接口。
因此,在以下示例中,customerPreferenceDao
field 首先查找 bean
命名为 “customerPreferenceDao”,然后回退到该类型的主要类型匹配项CustomerPreferenceDao
:
-
Java
-
Kotlin
public class MovieRecommender {
@Resource
private CustomerPreferenceDao customerPreferenceDao;
@Resource
private ApplicationContext context; (1)
public MovieRecommender() {
}
// ...
}
1 | 这context field 根据已知的 Resolvable 依赖项类型注入:ApplicationContext . |
class MovieRecommender {
@Resource
private lateinit var customerPreferenceDao: CustomerPreferenceDao
@Resource
private lateinit var context: ApplicationContext (1)
// ...
}
1 | 这context field 根据已知的 Resolvable 依赖项类型注入:ApplicationContext . |