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. 附錄