Javaベースのコンテナアノテーション
@Beanは、XML構成ファイルと同様に、Spring IOCコンテナーによって管理される新しいオブジェクトを構成および初期化するためのメソッドを識別します。<bean> </bean>
任意のメソッドにSpringの@Componentアノテーション付きクラスの@Beanアノテーションを付けることができます(可能な場合のみ)。
通常は@Configurationが使用されます。
Bean構成アイテムにコメントを付けることができます
@Bean(initMethod = "init")
@Bean(destroyMethod = "destroy")
package com.zjx.bean;
public class StringStore implements Store {
public void init(){
System.out.println("this is init...");
}
public void destroy(){
System.out.println("this is destroy");
}
package com.zjx.bean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StoreConfig {
@Bean(initMethod="init",destroyMethod="destroy")
public Store stringStore(){
return new StringStore();
}
}
リソースファイルの読み方
<context:annotation-config></context:annotation-config>
<context:property-placeholder location="classpath:/Spring/src/jdbc.properties"/>
<bean class="com.Appconfig"></bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
または、クラスにコメントを書きます。
package com.zjx.properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
@ImportResource("classpath:/Spring/src/jdbc.properties")
public class AppConfig {
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String passWord;
public DataSource dataSource(){
return new DriverManagerDataSource(url, userName, passWord);
}
}
@範囲
デフォルトの@Beanはシングルトン
@Scopeであり、 @ Scopeには別の属性proxyModeがあります。つまり、どのプロキシモードが使用されますか。
@Bean(name = "stringStore")
//基于接口interface,基于类的TARGET_CLASS。
@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Store stringStore() {
return new StringStore();
}
汎用ベースの自動アセンブリ
@Configuration
public class MyConfiguration{
@Bean
public StringStore stringStore(){
return new StringStore();
}
@Bean
public IntegerStore integerStore(){
return new IntegerStore();
}
}
@Autowired
private Store<String> s1;
@Autowired
private Store<Integer> s2;
@Autowired自動アセンブリを実行する場合、2つのストアs1とs2があり、1つ目は文字列、2つ目は整数です。つまり、この一般的な方法で、どのBeans1とs2が対応するかを指定します。s1ジェネリック型はStringを指定し、s1は上記のStringStoreに対応し、s2はIntegerStoreに対応します。
//在一个集合里边的Store对象泛型指定的都是Integer类型的
@Autowired
private List<Store<Integer>> s;
以前のクラスのいくつかを変更して、インターフェイスでTジェネリックを指定します。public interface Store<T> {}
public class StringStore implements Store<String> {
public void init() {
System.out.println("This is init.");
}
public void destroy() {
System.out.println("This is destroy.");
}
}
public class IntegerStore implements Store<Integer> {
}
StoreConfigクラスで宣言します
@Autowired
private Store<String> s1;
@Autowired
private Store<Integer> s2;
@Bean
public StringStore stringStore() {
return new StringStore();
}
@Bean
public IntegerStore integerStore() {
return new IntegerStore();
}
@Bean(name = "stringStoreTest")
// public StringStore stringStoreTest() {
public Store stringStoreTest() {
System.out.println("s1 : " + s1.getClass().getName());
System.out.println("s2 : " + s2.getClass().getName());
return new StringStore();
}
Autowire拡張コンテンツ、カスタム修飾子に関する注記
CustomeAutowireConfigurerは、BeanFactoryPostProcessorのサブクラスであり、これを使用して、独自の修飾子アノテーションタイプを登録できます(Springの@Qualifierアノテーションが使用されていない場合でも)。
<bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
<property name="customQualifierTypes">
<set>
<value>example.CustomQualifier</value>
</set>
</property>
</bean>
このクラスはクラスを指定します。このクラスにはcustomQualifierTypes属性があります。自分で定義した型を入れることができます。これはSetであることに注意してください。つまり、多くの型を入れることができます。
AutowireCandidateResolver
自動組み立ての候補を決定します。
- 各Beanによって定義されたautowire-candidate値
- どれ
<bean/>
デフォルト-autowire、候補者の - @Qualifierアノテーションを使用し、CustomAutowireConfigurerのカスタムタイプを使用します。
ほとんど使われません
JSRのサポート
@PostConstructおよび@PreDestroy
CommonAnnotationBeanPostProcessorは、JSR-250のライフサイクルアノテーション@Resourceを認識するだけでなく、CommonAnnotationBeanPostProcessorがSpringのApplicationContextに登録されている場合、Spring2.5での初期化と破棄のコールバックもサポートします。
public class CachingMovieLister{
@PostConstruct
public void populateMovieCache(){
//...
}
@PreDestroy
public void clearMovieCache(){
//...
}
}
//在初始化和销毁之前都会调用这两个注解所注解的方法。
アノテーションによって提供された名前はBean名に解決され、ApplicationContextのCommonAnnotationBeanPostProcessorによって検出および処理されます。
例:
@Repository
public class JsrDAO {
public void save() {
System.out.println("JsrDAO invoked.");
}
}
@Service
public class JsrService{
//没有DAO赋值,会出现空指针异常。
//一种是在成员变量上使用@Resource注解,还有一种是生成set方法,在这个方法上使用@Resource注解。
@Resource
private JsrDAO jsrDAO;//把DAO的实例注入到当前的实例中来
/*或
@Resource
public void setJsrDAO(JsrDAO jsrDAO) {
this.jsrDAO = jsrDAO;
}*/
public void save(){
System.out.println("JsrServie save");
jarDAO.save();
}
@PostConstruct
public void init() {
System.out.println("JsrServie init.");
}
@PreDestroy
public void destroy() {
System.out.println("JsrServie destroy.");
}
}
//单元测试
@Test
public void testSave() {
JsrServie service = getBean("jsrServie");
service.save();
}
最初にJsrServieinit。を出力し、次にsave()メソッド呼び出しを出力し、最後にJsrServiedestroyを出力します。
JSR330標準注釈を使用する
Spring
3.0以降、JSR330標準アノテーション(依存性注入アノテーション)をサポートし、そのスキャン方法はSpringアノテーションと一貫しています。JSR330の使用はjavax.injectパッケージに依存する必要があります。Mavenを
使用してインポートします。
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1.0</version>
</dependency>
@Inject
@Injectは@Autowiredと同等であり、クラス、プロパティ、メソッド、およびコンストラクターで使用できます。
import javax.inject.Inject
public class SimpleMovieLister{
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder=movieFinder;
}
}
@Named
依存性注入に特定の名前を使用する場合は、@ Namedを使用します。つまり、IOCコンテナーに同じタイプのBeanが複数ある場合、特定のBeanを使用する場合は、このアノテーションを使用できます。
@Namedと@Componentは同等です
//注解在类上
@Named("movieListener")
public class SimpleMovieLister{
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder=movieFinder;
}
}
//用来指定某一个名称的bean。和Qualifier有点类似
public class SimpleMovieLister{
private MovieFinder movieFinder;
@Inject
public void setMovieFinder(@Named("main")MovieFinder movieFinder){
this.movieFinder=movieFinder;
}
}
前の例で
は、JsrServiceクラスの@ServiceをNamedに変更でき、メンバー変数の@Resourceアノテーションと内部のsetメソッドを@Injectに変更でき、出力は変更されません。
// @Resource
@Inject
public void setJsrDAO(@Named("jsrDAO") JsrDAO jsrDAO) {
this.jsrDAO = jsrDAO;
}
ここで(@Named( "jsrDAO")を追加することもできます。効果は何ですか?
このJsrDAOクラスを追加すると、現在のIOCコンテナに2つのBeanが含まれるため、これを追加すると、2つの実装クラスを持つインターフェイスになります。すべてが挿入されます。前の例のStringStoreとIntegerStoreのように、現在のIOCコンテナーに入れると、どちらが名前付きであるかを参照できます。
参照:
Springの概要(SpringによるJSRサポートの説明)
https://blog.csdn.net/qq_36206746/article/details/78141904
https://blog.csdn.net/kang82651204/article/category/6070639