【Spring】Spring IoC アノテーション開発

[Power Node] の最新の Spring フレームワーク チュートリアル、ネットワーク全体での最初の Spring 6 チュートリアルに基づいて、Lao DuLao Du のオリジナル ノートで Spring をゼロから上級まで学習しますhttps://www.yuque.com/docs/share /866abad4-7106 -45e7-afcd-245a733b073f?# 「Spring6」が整理されています、文書パスワード: mg9b


春関連の記事はhttps://www.yuque.com/u27599042/zuisieにまとめてあります。


  • Spring6 は完全なアノテーション開発を提唱しています
  • 注釈は主に XML 構成を簡素化するために存在します。
  • 注釈は実際にはマークです

カスタム注釈を確認する

  • メタアノテーション: アノテーションに注釈を付けるアノテーション
  • @Target 注釈: 注釈が表示される位置を変更するために使用されます。
    • @Target(value = {ElementType.TYPE, ElementType.FIELD})、ターゲット アノテーションはクラスまたはフィールドに表示できます
    • @Target(value = {ElementType.TYPE})、ターゲット アノテーションはクラスに表示できます
  • アノテーションを使用する場合、アノテーションの属性名がvalueの場合はvalueを省略できます。
    • @Target({ElementType.TYPE})
  • アノテーションを使用する場合、アノテーションの属性値が配列であり、配列内に要素が 1 つだけある場合は、中括弧を省略できます。
    • @Target(ElementType.TYPE)
  • @Retention: これはメタアノテーションでもあり、アノテーションをいつ保持できるかをマークするために使用されます。
    • 注釈がクラス ファイルに保存され、リフレクション メカニズムで読み取れる場合は、 @Retention(RetentionPolicy.RUNTIME) を使用します。
    • @Retention(RetentionPolicy.SOURCE) は、Retention アノテーションのアノテーションがソース ファイルにのみ保持され、Retention アノテーションのアノテーションがバイトコードおよびランタイムでは表示されないことを示します。
  • カスタム注釈と定義された注釈プロパティ:
// 标注该注解可以用在类上
@Target(ElementType.TYPE)
// 标注@Component注解最终保留在class文件当中,并且可以被反射机制读取。
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
    
    

    // 定义注解的属性
    // String是属性类型
    // value是属性名
    String value();

    // 其他的属性
    // 属性类型String
    // 属性名是name
    //String name();

    // 数组属性
    // 属性类型是:String[]
    // 属性名:names
    //String[] names();

    //int[] ages();

    //int age();
}

カスタム注釈の使用を確認する

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
    
    
    String value();
}
@Component("user")
public class User {
    
    }

リフレクションを通じてアノテーションを取得する

@org.junit.Test
public void testGetAnnotationByReflect() throws Exception{
    
    
    // 将类加载到JVM中
    Class<?> clazz = Class.forName("cw.study.spring.bean.User");
    // 判断类上是否有自定义的Component注解
    if (clazz.isAnnotationPresent(Component.class)) {
    
    
        // 如果有,获取该注解
        Component component = clazz.getAnnotation(Component.class);
        // 获取该类上注解的属性值
        System.out.println(component.value());
    }
}

画像.png

コンポーネントのスキャン原理

  • 要件: パッケージ名を指定して、このパッケージの下で @Component アノテーションが付けられたすべてのクラスをインスタンス化します。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
    
    
    String value();
}
@Component("user")
public class User {
    
    }

@Component("cat")
public class Cat {
    
    }

public class Person {
    
    }
@org.junit.Test
public void componentScan() {
    
    
    // 已知的包名如下,需要扫描包下所有的类,将有Component注解的类实例化
    String packageName = "cw.study.spring.bean";
    // 包名其实就是目录名,将包名转化为目录
    // . 在正则中代表任意字符,需要进行转义,而 \\ 表示 \ 所以使用 \\.
    String directoryName = packageName.replaceAll("\\.", "/");
    // 软件包是在类路径下的,所以可以使用系统加载器加载目录获取URL
    URL url = ClassLoader.getSystemClassLoader().getResource(directoryName);
    // 通过URL获取包对应的绝对路径
    String path = url.getPath();
    System.out.println("path = " + path);
    // 根据绝对路径创建目录对应的对象
    File file = new File(path);
    // 获取目录下的文件对象
    File[] files = file.listFiles();
    System.out.println(files.length);
    // 遍历每个文件对象
    Arrays.stream(files).forEach(f -> {
    
    
        try {
    
    
            // 获取文件名
            String fName = f.getName();
            // System.out.println("fName = " + fName);
            // 得到类名
            String className = packageName + "." + fName.split("\\.")[0];
            // 加载类到JVM
            Class<?> clazz = Class.forName(className);
            // 判断类上是否有Component注解
            if (clazz.isAnnotationPresent(Component.class)) {
    
    
                // 获取注解
                Component component = clazz.getAnnotation(Component.class);
                // 获取注解的属性(Bean的id)
                String id = component.value();
                System.out.println(id);
                // 实例化对象
                Object o = clazz.getDeclaredConstructor().newInstance();
                System.out.println(o);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    });
}

Bean を宣言するためのアノテーション

  • Bean の宣言を担当するアノテーション。次の 4 つの一般的なアノテーションが含まれます。
    • @Component: コンポーネント
    • @Controller: コントローラー
    • @サービス:ビジネス
    • @リポジトリ:倉庫(Dao)
  • 上記 4 つのアノテーションのうち、@Controller、@Service、@Repository はすべて @Component (@AliasFor) のエイリアスです。実際、これら 4 つのアノテーションの機能は同じです。どれを使用しても構いませんが、異なるものを使用してください。注釈によってプログラムの可読性が向上します。
    • 普通 bean:Component
    • コントローラークラスで使用: コントローラー (制御層)
    • サービスクラスで使用: サービス (ビジネス層)
    • dao クラスで使用: リポジトリ (永続層)
  • 上記の 4 つのアノテーションには、Bean の ID を指定するために使用される value 属性が 1 つだけあります。
@Target({
    
    ElementType.TYPE}) // 只能使用在类上
@Retention(RetentionPolicy.RUNTIME) // 可以通过反射获取该注解
@Documented
@Indexed
public @interface Component {
    
    
    String value() default "";
}

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    
    
    // Component的别名
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    
    
    // Component的别名
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    
    
    // Component的别名
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

Spring アノテーションの使用

ステップ 1: AOP 依存関係を追加する

  • spring-context 依存関係が追加されると、aop 依存関係が自動的に関連付けられます。
  • 画像.png

ステップ 2: コンテキスト名前空間を構成ファイルに追加する

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

</beans>

ステップ 3: 構成ファイルでスキャンされたパッケージを指定する

  • 構成ファイルでスキャンされたパッケージを指定し、スキャンする必要があるパッケージがどこにあるかを Spring に伝えます。
  • Spring は、指定されたパッケージ内のクラスとそのサブパッケージ内のクラスをスキャンします。クラスが Bean を宣言するアノテーションでマークされている場合、クラスのインスタンスが作成され、Spring コンテナーに配置されます。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
						   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 指定扫描的包,告诉Spring需要进行扫描的包在什么位置 -->
	<context:component-scan base-package="cw.study.spring"/>
	
</beans>

ステップ 4: Bean クラスでアノテーションを使用する

@Component("user")
public class User {
    
    }

@Controller("userController")
public class UserController {
    
    }

テスト

@org.junit.Test
public void test01() {
    
    
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    Object user = applicationContext.getBean("user");
    Object userController = applicationContext.getBean("userController");
    System.out.println(user);
    System.out.println(userController);
}

画像.png

注意点

  • アノテーションの属性名が value の場合、value は省略できます。
  • value 属性が完全に削除された場合、Spring は自動的に Bean に名前を付けます。デフォルトの名前規則は、Bean クラス名の最初の文字は小文字にすることができます。
@Component
public class User {
    
    }

@Controller
public class UserController {
    
    }

@org.junit.Test
public void test02() {
    
    
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    Object user = applicationContext.getBean("user");
    Object userController = applicationContext.getBean("userController");
    System.out.println(user);
    System.out.println(userController);
}

画像.png

  • 複数のパッケージをスキャンする場合は、次の 2 つの解決策があります。
    • 1 つ目: 構成ファイル内で複数のパッケージをカンマで区切って指定します。
<context:component-scan base-package="cw.study.spring.bean, cw.study.spring.controller"/>
  • 2 番目のタイプ: 複数のパッケージの共通の親パッケージを指定します。
    • Spring は、指定されたパッケージ内のクラスとそのサブパッケージ内のクラスをスキャンします。
    • この方法を使用すると、効率がある程度犠牲になります
<context:component-scan base-package="cw.study.spring"/>

Bean の選択的なインスタンス化

  • Bean の選択的インスタンス化とは、Bean のインスタンス化に対して特定の条件を満たすクラスのみを選択すること、または特定の条件を満たすクラスを除外してこれらのクラスの Bean をインスタンス化しないことを意味します。
package cw.spring.bean;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/**
 * ClassName: A
 * Package: cw.spring.bean
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 11:42
 * @Version 1.0
 */
@Component
public class A {
    
    
    public A() {
    
    
        System.out.println("A的无参数构造方法执行");
    }
}

@Controller
class B {
    
    
    public B() {
    
    
        System.out.println("B的无参数构造方法执行");
    }
}

@Service
class C {
    
    
    public C() {
    
    
        System.out.println("C的无参数构造方法执行");
    }
}

@Repository
class D {
    
    
    public D() {
    
    
        System.out.println("D的无参数构造方法执行");
    }
}

@Controller
class E {
    
    
    public E() {
    
    
        System.out.println("E的无参数构造方法执行");
    }
}

方法 1: **use-default-filters="false" + **context:include-filter

  • use-default-filters="false": Spring のデフォルトのインスタンス化ルールを使用しません。つまり、宣言された Bean を持つすべてのアノテーションは無効になり、コンポーネント、コントローラー、サービス、およびリポジトリでアノテーションが付けられた Bean はインスタンス化されません (すべての宣言された Bean のアノテーションが無効です)
    • use-default-filters のデフォルト値は true です。
  • <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    • Component アノテーションが付けられた Bean がインスタンス化されていることを示します。
    • type 属性は、クラスをフィルタリングするための条件のタイプ、つまり、何に基づいてフィルタリングするかを指定するために使用されます。type="annotation"、クラスのアノテーションに基づいてフィルタリングします。
    • Expression 属性は、フィルタリング条件 (expression="org.springframework.stereotype.Component") を指定するために使用されます。Component アノテーションが付けられたクラスのみがインスタンス化されます。
  • 他の 3 つのアノテーションはコンポーネントのエイリアスにすぎないため、「コンポーネントを含む」には他の 3 つのアノテーションも含まれます。
  • 注: context:include-filter を使用する場合、use-default-filters の属性値は false でなければなりません。そうでない場合、context:include-filter は無効になります。
<!-- 指定要进行扫描的包 -->
<context:component-scan base-package="cw.spring.bean" use-default-filters="false">
  <!-- 被 Component 注解标注的 bean 进行实例化 -->
  <!-- 由于其他三个注解只是 Component 的别名,所以包含 Component 也就包含其他三种注解 -->
  <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/> -->
  <!-- 被 Controller 注解标注的 bean 进行实例化 -->
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

方式二:**use-default-filters=“true” + **context:exclude-filter

  • use-default-filters="true": Spring のデフォルトのインスタンス化ルールを使用します。つまり、宣言された Bean を持つすべてのアノテーションが有効になり、コンポーネント、コントローラー、サービス、およびリポジトリでアノテーションが付けられた Bean がインスタンス化されます。
    • use-default-filters のデフォルト値は true です。
  • <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    • コンポーネント アノテーションが付けられた Bean はインスタンス化されず、コンポーネント アノテーションが付けられた Bean は除外されることを示します。
  • 他の 3 つのアノテーションは Component のエイリアスにすぎないため、Component を除外すると、他の 3 つのアノテーションも除外されます。
<!-- 指定要进行扫描的包 -->
<context:component-scan base-package="cw.spring.bean">
  <!-- 排除被 Component 注解标注的 bean,这些 bean 不参与实例化 -->
  <!-- 由于其他三个注解只是 Component 的别名,所以排除 Component 也就排除了其他三种注解 -->
  <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/> -->
  <!-- 排除被 Controller 注解标注的 bean,这些 bean 不参与实例化 -->
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

インジェクションを担当するアノテーション

  • @Component @Controller @Service @Repository これら 4 つのアノテーションは Bean を宣言するためにのみ使用され、宣言後、これらの Bean はインスタンス化されます。
  • Bean のプロパティに値を割り当てるには、次のアノテーションを使用します。
    • @価値
    • @Autowired
    • @修飾子
    • @リソース

@価値

  • 簡易型注入
  • 属性の型が単純型の場合、注入に @Value アノテーションを使用できます。
  • @Value アノテーションが代わりに使用されます。<property name="" value=""/>
@Target({
    
    ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    
    
	String value();
}
属性で使用される
  • @value は、対応する set メソッドを提供せずに、属性に直接書き込むことができます。
package cw.spring.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * ClassName: MyDataSource
 * Package: cw.spring.bean
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:13
 * @Version 1.0
 */
@Component
public class MyDataSource {
    
    
    @Value("com.mysql.cj.jdbc.Driver")
    private String driver;
    @Value("jdbc:mysql://localhost:3306/spring")
    private String url;
    @Value("root")
    private String username;
    @Value("123456")
    private String password;
    
    @Override
    public String toString() {
    
    
        return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
    }
}
setメソッドで使用される
  • 属性に対応するsetメソッドに@valueを記述することで属性値の注入を実現することもできます。
  • コードを簡素化するために、通常、set メソッドは提供されず、 @Value アノテーションを属性に直接使用して属性の割り当てを完了します。
package cw.spring.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * ClassName: MyDataSource
 * Package: cw.spring.bean
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:13
 * @Version 1.0
 */
@Component
public class MyDataSource {
    
    
    private String driver;
    private String url;
    private String username;
    private String password;
    
    @Value("com.mysql.cj.jdbc.Driver")
    public void setDriver(String driver) {
    
    
        this.driver = driver;
    }
    
    @Value("jdbc:mysql://localhost:3306/spring")
    public void setUrl(String url) {
    
    
        this.url = url;
    }
    
    @Value("root")
    public void setUsername(String username) {
    
    
        this.username = username;
    }
    
    @Value("123456")
    public void setPassword(String password) {
    
    
        this.password = password;
    }
    
    @Override
    public String toString() {
    
    
        return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
    }
}
コンストラクターメソッドの仮パラメーターで使用されます
  • @Value アノテーションは、コンストラクター メソッドの仮パラメーターでも使用できます。
package cw.spring.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * ClassName: MyDataSource
 * Package: cw.spring.bean
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:13
 * @Version 1.0
 */
@Component
public class MyDataSource {
    
    
    private String driver;
    private String url;
    private String username;
    private String password;
    
    public MyDataSource(
            @Value("com.mysql.cj.jdbc.Driver") String driver, 
            @Value("jdbc:mysql://localhost:3306/spring") String url, 
            @Value("root") String username, 
            @Value("123123") String password
    ) {
    
    
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }
    
    @Override
    public String toString() {
    
    
        return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
    }
}

@Autowired

  • @Autowired アノテーションは、非単純型を挿入するために使用されます。
    • Autowired: 自動配線または自動組み立て
    • @Autowired、注釈による自動アセンブリ
  • @Autowired アノテーションには set メソッドは必要ありません
  • @Autowired アノテーションのみを使用すると、デフォルトのアセンブリは type に基づき、つまり、デフォルトは byType になります。名前に基づいて自動的にアセンブルする必要がある場合は、 @Qualifier アノテーションを使用する必要があります。
  • @Autowired アノテーションは、タイプに基づいて自動的にアセンブルされます。@Autowired アノテーションのみを使用する場合、同じタイプの 2 つのインスタンスが Spring コンテナーに存在することはできません。@Autowired アノテーションを使用する場合、およびSpring コンテナー内の同じ型の場合は、 @Qualifier アノテーションを使用して名前に基づいてアセンブルする必要があります
  • このアノテーションはコンストラクタ、メソッド、仮パラメータ、属性、アノテーション上にマークすることができ、使用方法や記述位置は@Valueと同様です。
  • このアノテーションには必須の属性があり、デフォルト値は true であり、注入された Bean が注入時に存在する必要があることを意味し、存在しない場合はエラーが報告されます。required 属性が false に設定されている場合、注入された Bean が存在するかどうかは関係ないことを意味します。存在する場合は注入され、存在しない場合はエラーは報告されません。
@Target({
    
    ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    
    
    boolean required() default true;
}
  • @Autowired アノテーションを使用する場合、属性を指定せずに直接使用できます。
/**
 * ClassName: OrderDao
 * Package: cw.spring.dao
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:50
 * @Version 1.0
 */
public interface OrderDao {
    
    
    void insert();
}
/**
 * ClassName: OrderDaoImplForMySQL
 * Package: cw.spring.dao.impl
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:50
 * @Version 1.0
 */
@Repository
public class OrderDaoImplForMySQL implements OrderDao {
    
    
    @Override
    public void insert() {
    
    
        System.out.println("MySQL数据库正在保存订单信息...");
    }
}
import cw.spring.dao.OrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName: OrderService
 * Package: cw.spring.service
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:49
 * @Version 1.0
 */
@Service("orderService")
public class OrderService {
    
    
    @Autowired
    private OrderDao orderDao;
    
    public void save() {
    
    
        orderDao.insert();
    }
}
  • クラス内にコンストラクタが 1 つしかなく、コンストラクタ上のパラメータと注入​​する必要のある属性が一致する場合は @Autowired アノテーションを省略できますが、コンストラクタが複数ある場合は @Autowired アノテーションを省略できません。
  • 省略しないことをお勧めします。プログラムが読みやすくなります。
/**
 * ClassName: OrderService
 * Package: cw.spring.service
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:49
 * @Version 1.0
 */
@Service("orderService")
public class OrderService {
    
    
    // @Autowired
    // @Qualifier("orderDaoImplForOracle")
    private OrderDao orderDao;
    
    public OrderService(OrderDao orderDao) {
    
    
        this.orderDao = orderDao;
    }
    
    public void save() {
    
    
        orderDao.insert();
    }
}

@修飾子

  • @Autowired アノテーションと @Qualifier アノテーションを組み合わせて名前を元にアセンブルし、@Qualifier アノテーションに Bean 名を指定します。
/**
 * ClassName: OrderDaoImplForOracle
 * Package: cw.spring.dao.impl
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:59
 * @Version 1.0
 */
@Repository
public class OrderDaoImplForOracle implements OrderDao {
    
    
    @Override
    public void insert() {
    
    
        System.out.println("Oracle数据库正在保存订单信息...");
    }
}
/**
 * ClassName: OrderService
 * Package: cw.spring.service
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 12:49
 * @Version 1.0
 */
@Service("orderService")
public class OrderService {
    
    
    @Autowired
    @Qualifier("orderDaoImplForOracle")
    private OrderDao orderDao;
    
    public void save() {
    
    
        orderDao.insert();
    }
}

@リソース

  • @Resource アノテーションは、非単純型の注入を完了できます。
  • @Resource アノテーションは JDK 拡張パッケージに含まれており、これは JDK の一部であることを意味しますが、@Autowired アノテーションは Spring フレームワーク独自のものです。
  • @Resource は JDK 標準仕様に含まれており、より汎用性が高く、より推奨されます。
  • @Resource アノテーションは、デフォルトでは名前に基づいて Name によってアセンブルされます。name が指定されていない場合は、属性名が名前として使用されます。名前で見つからない場合は、タイプ byType によるアセンブリが自動的に開始されます。
  • @Resource アノテーションは、プロパティ、セッター メソッド、およびメソッドで使用されます
@Target({
    
    ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
    
    
    String name() default "";

    String lookup() default "";

    Class<?> type() default Object.class;

    AuthenticationType authenticationType() default Resource.AuthenticationType.CONTAINER;

    boolean shareable() default true;

    String mappedName() default "";

    String description() default "";

    public static enum AuthenticationType {
    
    
        CONTAINER,
        APPLICATION;

        private AuthenticationType() {
    
    
        }
    }
}
  • @Resource アノテーションは JDK 拡張パッケージに属しているため、JDK には含まれていません。次の追加の依存関係を導入する必要があります。
    • 拡張依存関係を導入する
    • JDK8の場合は追加の依存関係を導入する必要はありませんが、JDK11以上またはJDK8未満の場合は以下の依存関係を導入する必要があります。
<dependency>
  <groupId>jakarta.annotation</groupId>
  <artifactId>jakarta.annotation-api</artifactId>
  <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>javax.annotation</groupId>
  <artifactId>javax.annotation-api</artifactId>
  <version>1.3.2</version>
</dependency>
/**
 * ClassName: StudentDao
 * Package: cw.spring.dao
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 16:03
 * @Version 1.0
 */
public interface StudentDao {
    
    
    void deleteById();
}
/**
 * ClassName: StudentDaoImplForMySQL
 * Package: cw.spring.dao.impl
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 16:04
 * @Version 1.0
 */
@Repository
public class StudentDaoImplForMySQL implements StudentDao {
    
    
    @Override
    public void deleteById() {
    
    
        System.out.println("MySQL数据库正在删除学生信息...");
    }
}
/**
 * ClassName: StudentService
 * Package: cw.spring.service
 * Description:
 *
 * @Author tcw
 * @Create 2023-05-14 16:05
 * @Version 1.0
 */
@Service
public class StudentService {
    
    
    // name属性用于指定将要被注入到该属性的Bean的名字
    @Resource(name = "studentDaoImplForMySQL")
    private StudentDao studentDao;
    
    public void delete() {
    
    
        studentDao.deleteById();
    }
}

完全なアノテーション開発

  • 完全なアノテーション開発とは、Spring 構成ファイルを使用しなくなり、構成ファイルを置き換える構成クラスを作成することを意味します。

@Configuration アノテーション アノテーション構成クラス

  • 構成クラスには @Configuration アノテーションが付けられます
@Configuration
public class Spring6Config {
    
    
}

@ComponentScan アノテーションはスキャンされたパッケージを構成します

  • @ComponentScan アノテーションを使用してパッケージをスキャンするように構成します。
@Configuration
@ComponentScan({
    
    "cw.spring.dao", "cw.spring.service"})
public class Spring6Config {
    
    
}

完全なアノテーション開発で Spring コンテナを取得する

  • スプリングコンテナの入手はnew ClassPathXmlApplicationContext()もはや目的ではありませんが、new AnnotationConfigApplicationContext()
@org.junit.Test
public void test03() {
    
    
    // 获取Spring容器对象时,需要传配置类为参数
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config.class);
    StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
    studentService.delete();
}

おすすめ

転載: blog.csdn.net/m0_53022813/article/details/132058759