6、依存性注入
概念
- 依存性注入(DI)。
- 依存関係:Beanオブジェクトの作成は、コンテナーに依存します。Beanオブジェクトの依存リソース。
- インジェクション:Beanオブジェクトが依存するリソースを指します。これは、コンテナーによって設定およびアセンブルされます。
コンストラクター注入
私は前にそれについて話しました
セットインジェクション(強調)
注入する必要のあるプロパティにはsetメソッドが必要です。setメソッドのメソッド名はset + propertyで大文字になります。プロパティがブール型で、setメソッドがない場合は、です。
pojoクラスのテスト:
Address.java
package com.kuber.pojo;
public class Address {
private String homeAddress;
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
@Override
public String toString() {
return "Address{" +
"homeAddress='" + homeAddress + '\'' +
'}';
}
}
Student.java:
package com.kuber.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String girlfriend;
private Properties info;
public String getGirlfriend() {
return girlfriend;
}
public void setGirlfriend(String girlfriend) {
this.girlfriend = girlfriend;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address.toString() +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", info=" + info +
'}';
}
}
学生のさまざまな属性がbeans.xmlに1つずつ比較されます。
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="userbeans.xml"/>
<import resource="employee-beans.xml"/>
<bean id="address" class="com.kuber.pojo.Address">
<property name="homeAddress" value="河南"/>
</bean>
<!--Bean注入,注意点:这里的值是一个引用,ref-->
<bean id="student" class="com.kuber.pojo.Student">
<property name="name" value="倪文翰"/>
<property name="address" ref="address"/>
<property name="books">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>水浒传</value>
<value>西游记</value>
</array>
</property>
<property name="hobbies">
<list>
<value>敲代码</value>
<value>看书</value>
<value>打游戏</value>
</list>
</property>
<property name="card">
<map>
<entry key="身份证" value="46541651"/>
<entry key="学生证" value="201619823"/>
</map>
</property>
<property name="games">
<set>
<value>GTA5</value>
<value>LOL</value>
<value>CS:GO</value>
</set>
</property>
<property name="girlfriend" value="gyy"/>
<property name="info">
<props>
<prop key="username">root</prop>
<prop key="password">root</prop>
<prop key="driver">dddd</prop>
<prop key="url">aqwer</prop>
</props>
</property>
</bean>
</beans>
テストコード:
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
/*Student{
name='倪文翰',
address=Address{homeAddress='河南'},
books=[红楼梦, 三国演义, 水浒传, 西游记],
hobbies=[敲代码, 看书, 打游戏],
card={身份证=46541651, 学生证=201619823},
games=[GTA5, LOL, CS:GO],
info={password=root, url=aqwer, driver=dddd, username=root}
}
*/
}
試験結果:
pネーミングとcネーミングインジェクション
User.java:[注:ここにはパラメーターコンストラクターはありません!】
public class User {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
P名前空間インジェクション:ヘッダーファイルに制約ファイルを追加する必要があります
c名前空間インジェクション:ヘッダーファイルに制約ファイルを追加する必要があります
<?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"
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="user" class="com.kuber.pojo.User" p:username="工藤静香" p:age="20"/>
<bean id="user2" class="com.kuber.pojo.User" c:username="工藤胖虎" c:age="40" scope="singleton"/>
<!--默认单例模式,scope=singleton""-->
</beans>
問題が見つかりました:人気があります。今はパラメータ構造を記述していません。
解決策:パラメーター化されたコンストラクターを追加します。ここでもわかります。cはいわゆるコンストラクターインジェクションです。
テストコード:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
}
[
Beanスコープ
Springでは、アプリケーションの本体とSpringIoCコンテナーによって管理されるオブジェクトはBeanと呼ばれます。簡単に言うと、Beanは、IoCコンテナーによって初期化、アセンブル、および管理されるオブジェクトです。
いくつかのスコープの中で、リクエストスコープとセッションスコープはWebベースのアプリケーションでのみ使用され(使用しているWebアプリケーションフレームワークは関係ありません)、WebベースのSpringApplicationContext環境でのみ使用できます。
-
シングルトン
Beanのスコープがシングルトンの場合、Spring IoCコンテナーには共有Beanインスタンスが1つだけあり、IDがBean定義と一致する限り、Beanへのすべての要求はBeanの同じインスタンスのみを返します。シングルトンはシングルトンタイプです。つまり、コンテナが作成されると、同時にBeanオブジェクトが自動的に作成されます。使用するかどうかに関係なく存在し、毎回取得されるオブジェクトは同じオブジェクトです。シングルトンスコープがSpringのデフォルトスコープであることに注意してください。BeanをXMLでシングルトンとして定義するには、次のように構成できます。
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
-
プロトタイプ
BeanのスコープがPrototypeの場合、Bean定義が複数のオブジェクトインスタンスに対応していることを意味します。プロトタイプスコープのBeanは、Beanが要求されるたびに(別のBeanに注入されるか、コンテナーのgetBean()メソッドがプログラムで呼び出されるたびに)新しいBeanインスタンスを作成します。プロトタイプはプロトタイプタイプであり、コンテナの作成時にインスタンス化されません。代わりに、Beanを取得するときにオブジェクトを作成し、取得するオブジェクトは毎回同じオブジェクトではありません。経験によれば、ステートフルBeanにはプロトタイプスコープを使用し、ステートレスBeanにはシングルトンスコープを使用する必要があります。BeanをXMLのプロトタイプとして定義します。これは、次のように構成できます。
<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/> 或者 <bean id="account" class="com.foo.DefaultAccount" singleton="false"/>
-
リクエスト
BeanのスコープがRequestの場合、HTTPリクエストでは、Bean定義がインスタンスに対応します。つまり、各HTTPリクエストには、特定のBean定義に基づいて作成された独自のBeanインスタンスがあります。このスコープは、WebベースのSpringApplicationContextの場合にのみ有効です。次のBean定義を検討してください。
<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>
SpringコンテナはHTTPリクエストごとに、loginAction Beanの定義に基づいて新しいLoginAction Beanインスタンスを作成し、loginAction Beanインスタンスは現在のHTTPリクエストでのみ有効であるため、作成されたインスタンスの内部状態を安全に変更できます。他のリクエストでは、loginAction Bean定義に従って作成されたインスタンスは、特定のリクエストに固有のこれらの状態の変化を認識しません。リクエストの処理が終了すると、リクエストスコープ内のBeanインスタンスは破棄されます。
-
セッション
BeanのスコープがSessionの場合、Bean定義がHTTPセッションのインスタンスに対応することを意味します。このスコープは、WebベースのSpringApplicationContextの場合にのみ有効です。次のBean定義を検討してください。
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
特定のHTTPセッションの場合、SpringコンテナはuserPreferences Bean定義に基づいて新しいuserPreferencesBeanインスタンスを作成し、userPreferencesBeanは現在のHTTPセッションでのみ有効です。リクエストスコープと同様に、作成されたインスタンスの内部状態を必要に応じて安全に変更できます。userPreferencesに基づいて作成された他のHTTPセッションでは、HTTPセッションに固有のこれらの状態の変化は認識されません。HTTPセッションが最終的に破棄されると、HTTPセッションのスコープ内のBeanも破棄されます。