Spring从3.0开始提供 JSR-330标准的注释。(依赖注入)
需要添加
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
1.11.1 使用 @Inject 和@Named 配置依赖注入
替换@Autowired, @javax.inject.Inject 用法如下:
import javax.inject.Inject;
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
public void listMovies() {
this.movieFinder.findMovies(...);
...
}
}
}
和@Autowired一样, 也可以在字段层级、方法层级和构造参数层级使用@Inject,
使用@Name 指定Bean
import javax.inject.Inject;
import javax.inject.Named;
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(@Named("main") MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
}
和@Autowired一样, @Inject同样可以使用java.util.Optional和 @Nullable。
1.11.2 @Named and @ManagedBean 与 @Component注释等效
import javax.inject.Inject;
import javax.inject.Named;
@Named("movieListener") // @ManagedBean("movieListener") could be used as well
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
}
1.11.3 JSR-330标准注释的局限
Spring
javax.inject.*
javax.inject restrictions / comments
@Autowired
@Inject
@Inject has no 'required' attribute; can be used with Java 8’s Optionalinstead.
@Component
@Named / @ManagedBean
JSR-330 does not provide a composable model, just a way to identify named components.
@Scope("singleton")
@Singleton
The JSR-330 default scope is like Spring’s prototype. However, in order to keep it consistent with Spring’s general defaults, a JSR-330 bean declared in the Spring container is a singleton by default. In order to use a scope other than singleton, you should use Spring’s @Scopeannotation. javax.inject also provides a @Scope annotation. Nevertheless, this one is only intended to be used for creating your own annotations.
@Qualifier
@Qualifier / @Named
javax.inject.Qualifier is just a meta-annotation for building custom qualifiers. Concrete String qualifiers (like Spring’s @Qualifier with a value) can be associated through javax.inject.Named.
@Value
-
no equivalent
@Required
-
no equivalent
@Lazy
-
no equivalent
ObjectFactory
Provider
javax.inject.Provider is a direct alternative to Spring’s ObjectFactory, just with a shorter get() method name. It can also be used in combination with Spring’s @Autowired or with non-annotated constructors and setter methods
- 空白目录
- 0.环境准备
- 0.1基于maven的工程创建
- 1.控制反转容器
- 1.1 Spring控制反转容器和beans介绍
- 1.2 容器概览
- 1.3 Bean概览
- 1.4 依赖
- 1.5 Bean的范围
- 1.6 客制bean的特性
- 1.7 Bean定义的继承
- 1.8 容器扩展点
- 1.9 基于注解的容器配置
- 1.10 类路径扫描及组件管理
- 1.11 使用JSR 330标准的注解
- 1.12 基于Java的容器配置
- 1.12.1 基本概念: @Bean 和 @Configuration
- 1.13 环境抽象化
- 1.14 注册一个LoadTimeWeaver
- 1.15 ApplicationContext的附加功能
- 1.16 BeanFactory
- 2. 资源
- 3. 验证,数据绑定和类型转换
- 4. Spring表达式语言(SpEL)
- 5. Spring面向方面的切面编程
- 6. Spring AOP 接口
- 7. 空安全
- 8. 数据缓冲和编码
- 9. 附录