前回の記事では、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;
}
そして、対応する生成get
、set
および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>
テスト関数は変更されません。結果は次のとおりです。