共通点:
@Resourceと@Autowiredは両方ともBeanインジェクションに使用されます
@Resourceと@Autowiredの両方をフィールドとメソッドでマークできます
差:
@AutowiredはSpringによって提供されるアノテーションであり、インポートされた依存関係はorg.springframework.beans.factory.annotation.Autowiredです。
@ResourceはJ2EEによって提供され、インポートされた依存関係はjavax.annotation.Resourceです。
@Autowiredアノテーションは、デフォルトでタイプ(byType)に従って依存オブジェクトをアセンブルします。Springコンテナに指定された属性と同じタイプのBeanがある場合、その属性で自動的にアセンブルされます。このタイプのBeanが複数ある場合、例外がスローされます。デフォルトでは、@ Autowiredでは依存オブジェクトが存在する必要があります。存在しない場合は例外がスローされます。もちろん、@ Autowiredアノテーションの必須属性(これはAutowiredアノテーションの唯一の属性でもあります)を設定して設定することもできます。 falseする必要があります。
@Autowiredのソースコードは次のとおりです。
@Target({
ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
@Resourceは、デフォルトで名前(byName)による自動アセンブリになります。Springコンテナ内の@Resource属性名と同じBean名のBeanを検索し、@ Resourceでマークされた属性に自動的にアセンブルします。byName構成に加えて、@ ResourceはbyType構成もサポートします。@ Resourceアノテーションのtype属性を構成するだけで済みます。
以下に、@ Resourceのアセンブリシーケンスについて説明します。
①名前とタイプの両方が指定されている場合、一致するBeanのみがアセンブリのSpringコンテキストから検出され、見つからない場合は例外がスローされます。
②名前が指定されている場合、名前(id)に一致するBeanがコンテキストから検索されてアセンブリされ、見つからない場合は例外がスローされます。
③タイプが指定されている場合、アセンブリのコンテキストから類似する一致するBeanのみが見つかります。見つからない場合、または複数見つかった場合は、例外がスローされます。
④名前もタイプも指定されていない場合はbyNameメソッドで自動的にアセンブルされ、一致しない場合は元のタイプにフォールバックして照合され、一致した場合は自動的にアセンブルされます。
@Resourceのソースコードは次のとおりです。
@Target({
TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
/**
* The JNDI name of the resource. For field annotations,
* the default is the field name. For method annotations,
* the default is the JavaBeans property name corresponding
* to the method. For class annotations, there is no default
* and this must be specified.
*/
String name() default "";
/**
* The Java type of the resource. For field annotations,
* the default is the type of the field. For method annotations,
* the default is the type of the JavaBeans property.
* For class annotations, there is no default and this must be
* specified.
*/
Class<?> type() default java.lang.Object.class;
....省略其他属性字段
}