Springコアアノテーション

Spring Coreアノテーション

1. 概要

org.springframework.beans.factory.annotation およびorg.springframework.context.annotationパッケージのアノテーションを使用して、SpringDIエンジンの機能を活用できます。

これらは「Springコアアノテーション」と呼ばれることが多く、このチュートリアルで確認します。

2.1. @Autowired

@Autowiredからmark a dependency which Spring is going to resolve and injectを使用できます。 この注釈は、コンストラクター、セッター、またはフィールドインジェクションで使用できます。

コンストラクター注入:

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

セッター注入:

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

フィールド注入:

class Car {
    @Autowired
    Engine engine;
}

@Autowiredには、requiredと呼ばれるboolean引数があり、デフォルト値はtrueです。 配線に適したBeanが見つからない場合、Springの動作を調整します。 trueの場合、例外がスローされます。それ以外の場合、何も配線されません。

コンストラクター注入を使用する場合、すべてのコンストラクター引数が必須であることに注意してください。

バージョン4.3以降では、少なくとも2つのコンストラクターを宣言しない限り、コンストラクターに@Autowiredで明示的に注釈を付ける必要はありません。

詳細については、@Autowiredおよびconstructor injectionに関する記事をご覧ください。

2.2. @Bean

@Beanは、SpringBeanをインスタンス化するファクトリメソッドをマークします。

@Bean
Engine engine() {
    return new Engine();
}

戻り値の型の新しいインスタンスが必要な場合はSpring calls these methods

結果のBeanの名前は、ファクトリメソッドと同じです。 別の名前を付けたい場合は、このアノテーションのnameまたはvalue引数を使用して名前を付けることができます(引数valueは引数nameのエイリアスです) :

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

@Beanアノテーションが付けられたすべてのメソッドは、@Configurationクラスに含まれている必要があることに注意してください。

2.3. @Qualifier

あいまいな状況で使用したい@Autowiredからprovide the bean id or bean nameとともに@Qualifierを使用します。

たとえば、次の2つのBeanは同じインターフェースを実装します。

class Bike implements Vehicle {}

class Car implements Vehicle {}

SpringがVehicle Beanを注入する必要がある場合、複数の一致する定義が作成されます。 このような場合、@Qualifierアノテーションを使用してBeanの名前を明示的に指定できます。

コンストラクター注入の使用:

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

セッター注入の使用:

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

あるいは

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}

フィールドインジェクションの使用:

@Autowired
@Qualifier("bike")
Vehicle vehicle;

詳細な説明については、this articleをお読みください。

2.4. @Required

XMLを介して入力する依存関係をマークするsetterメソッドの@Required

@Required
void setColor(String color) {
    this.color = color;
}

    

それ以外の場合は、BeanInitializationExceptionがスローされます。

2.5. @Value

@Valueを使用してプロパティ値をBeanに挿入できます。 コンストラクター、セッター、フィールドインジェクションと互換性があります。

コンストラクター注入:

Engine(@Value("8") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

セッター注入:

@Autowired
void setCylinderCount(@Value("8") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

あるいは

@Value("8")
void setCylinderCount(int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

フィールド注入:

@Value("8")
int cylinderCount;

もちろん、静的な値を挿入することは役に立ちません。 したがって、@Valueplaceholder stringsを使用して、たとえば.propertiesまたは.yamlファイルの値defined in external sourcesをワイヤリングできます。

次の.propertiesファイルを想定します。

engine.fuelType=petrol

次のようにengine.fuelTypeの値を挿入できます。

@Value("${engine.fuelType}")
String fuelType;

SpELでも@Valueを使用できます。 より高度な例は、article about @Valueにあります。

2.6. @DependsOn

このアノテーションを使用して、Springinitialize other beans before the annotated oneを作成できます。 通常、この動作は、Bean間の明示的な依存関係に基づいて自動的に行われます。

このアノテーションwhen the dependencies are implicitのみが必要です。たとえば、JDBCドライバーのロードや静的変数の初期化などです。

依存関係Beanの名前を指定する依存クラスで@DependsOnを使用できます。 アノテーションのvalue引数には、依存関係Bean名を含む配列が必要です。

@DependsOn("engine")
class Car implements Vehicle {}

または、@Beanアノテーションを付けてBeanを定義する場合、ファクトリメソッドに@DependsOnアノテーションを付ける必要があります。

@Bean
@DependsOn("fuel")
Engine engine() {
    return new Engine();
}

2.7. @Lazy

Beanを遅延初期化する場合は、@Lazyを使用します。 デフォルトでは、Springはアプリケーションコンテキストの起動/ブートストラップ時にすべてのシングルトンBeanを積極的に作成します。

ただし、we need to create a bean when we request it, not at application startupの場合があります。

この注釈は、正確に配置した場所によって動作が異なります。 私たちはそれを置くことができます:

  • メソッド呼び出しを遅らせるための@Beanアノテーション付きBeanファクトリメソッド(したがって、Beanの作成)

  • @Configurationクラスとそれに含まれるすべての@Beanメソッドが影響を受けます

  • @Configurationクラスではない@Componentクラス、このBeanは遅延初期化されます

  • 依存関係自体を遅延的にロードするための@Autowiredコンストラクター、セッター、またはフィールド(プロキシ経由)

この注釈には、デフォルト値がtruevalueという名前の引数があります。 デフォルトの動作をオーバーライドすると便利です。

たとえば、グローバル設定が遅延しているときにBeanを積極的にロードするようにマークしたり、特定の@Beanメソッドを構成して@Lazyでマークされた@Configurationクラスに積極的にロードしたりします。

@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

詳細については、this articleにアクセスしてください。

2.8. @Lookup

@Lookupアノテーションが付けられたメソッドは、メソッドを呼び出すときにメソッドの戻り値の型のインスタンスを返すようにSpringに指示します。

注釈can be found in this articleに関する詳細情報。

2.9. @Primary

同じタイプの複数のBeanを定義する必要がある場合があります。 これらの場合、Springには必要なBeanの手がかりがないため、注入は失敗します。

このシナリオに対処するオプションはすでに見ました。すべての配線ポイントを@Qualifierでマークし、必要なBeanの名前を指定します。

ただし、ほとんどの場合、特定のBeanが必要であり、他のBeanはほとんど必要ありません。 このケースを単純化するために@Primaryを使用できます。we mark the most frequently used bean with @Primaryの場合、修飾されていない注入ポイントで選択されます。

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    Vehicle vehicle;
}

@Component
class Biker {
    @Autowired
    @Qualifier("bike")
    Vehicle vehicle;
}

前の例では、Carが主要な車両です。 したがって、Driverクラスでは、SpringはCarBeanを注入します。 もちろん、Biker Beanでは、フィールドvehicleの値は修飾されているため、Bikeオブジェクトになります。

2.10. @Scope

@Scopeを使用して、@Componentクラスのscopeまたは@Bean定義.を定義します。singleton, prototype, request, session, globalSessionまたはカスタムスコープのいずれかです。

例えば:

@Component
@Scope("prototype")
class Engine {}

3. コンテキスト設定アノテーション

このセクションで説明する注釈を使用して、アプリケーションコンテキストを構成できます。

3.1. @Profile

Springをuse a @Component class or a @Bean method only when a specific profile is activeにしたい場合は、@Profileでマークできます。 プロファイルの名前は、注釈のvalue引数を使用して構成できます。

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

プロファイルの詳細については、this articleを参照してください。

3.2. @Import

このアノテーションでspecific @Configuration classes without component scanningを使用できます。 これらのクラスに@Importvalue引数を提供できます。

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

3.3. @ImportResource

このアノテーションを使用してimport XML configurationsを実行できます。 XMLファイルの場所は、locations引数、またはそのエイリアスであるvalue引数を使用して指定できます。

@Configuration
@ImportResource("classpath:/annotations.xml")
class VehicleFactoryConfig {}

3.4. @PropertySource

この注釈を使用すると、define property files for application settingsを実行できます。

@Configuration
@PropertySource("classpath:/annotations.properties")
class VehicleFactoryConfig {}

@PropertySourceは、Java 8の繰り返しアノテーション機能を利用します。つまり、クラスに複数回マークを付けることができます。

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

3.5. @PropertySources

このアノテーションを使用して、複数の@PropertySource構成を指定できます。

@Configuration
@PropertySources({
    @PropertySource("classpath:/annotations.properties"),
    @PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

Java 8以降では、上記のようにアノテーションの繰り返し機能を使用して同じことを実現できることに注意してください。

4. 結論

この記事では、最も一般的なSpringコア注釈の概要を見ました。 Beanのワイヤリングとアプリケーションコンテキストの構成方法、およびコンポーネントスキャン用のクラスのマーク方法について説明しました。

いつものように、例は利用可能なover on GitHubです。