SpringのIoC(制御の反転)4-pおよびc名前空間

前回の記事では、SpringインジェクションにはコンストラクターインジェクションとSetモードインジェクションがあり、これら2種類のインジェクトで簡単なケースプラクティスが実行された述べました。 ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ?????????????????????????????????????????????????? ????????????? 上記の2つの注入方法を作成するには、2つの簡単な方法があります。

1.コンストラクタインジェクションの場合

これは、c-namespace以前に学習したコンストラクター注入メソッドに対応する公式ドキュメントで呼び出されます。公式文書アドレス:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-c-namespace
制約を導入した最初の必要性xmlns:c="http://www.springframework.org/schema/c"使用し、その後、およびc:として、それをUser.javaで定義されています:

private int age;
private String name;

public User() {
    
    
}

public User(int age, String name) {
    
    
    this.age = age;
    this.name = name;
}

そして、対応する生成getsetおよびtoString方法を、次に、中、我々beans.xmlのファイル:

<?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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="weizu" class="com.weizu.pojo.User" c:age="12" c:name="战三"></bean>
</beans>

テスト:

public class myTest {
    
    

    @Test
    public void Test(){
    
    
        // create and configure beans
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User userService = (User) context.getBean("weizu");
        System.out.println(userService.toString());
    }
}

ここに画像の説明を挿入

2.Setバージョン

p-namespace単純化するために使用します。setプロパティインジェクションは、デフォルトでパラメーターなしのコンストラクターを使用し、次にsetメソッドを使用して値をインジェクトします。アドレス:https//docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace同様に、制約は最初に導入する必要があります:xmlns:p="http://www.springframework.org/schema/p"、次にp:ユースケース:

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="weizu" class="com.weizu.pojo.User" p:age="12" p:name="战三"></bean>
</beans>

テスト関数は変更されません。結果は次のとおりです。
ここに画像の説明を挿入


ビデオアドレス:https//www.bilibili.com/video/BV1WE411d7Dv?p = 10

おすすめ

転載: blog.csdn.net/qq_26460841/article/details/115050585