コンストラクターに基づく依存性注入:
使用される
ラベル:コンストラクター引数の位置ラベル:Bean
ラベルの内部ラベルの属性:
- type:注入されるデータのデータ型を指定するために使用されます。これは、コンストラクターの1つまたはいくつかのパラメーターの型でもあります。
- index:コンストラクターの指定されたインデックス位置のパラメーターに注入されるデータを指定するために使用されます。インデックス位置は0から始まります。
- name:コンストラクターで指定された名前のパラメーターに値を割り当てるために使用されます。(よく使われる)
- 値:基本タイプと文字列タイプのデータを提供するために使用されます
- ref:他のBeanタイプのデータを指定するために使用されます。これは、Spring IoCコアコンテナーに表示されたBeanオブジェクトを参照します。
機能(利点):Beanオブジェクトを取得する場合、データの注入は必要な操作です。そうでない場合、オブジェクトを正常に作成できません。
短所:Beanオブジェクトのインスタンス化を変更したため、オブジェクトを作成するときに、データを使用できない場合はそれらを提供する必要があります。
例:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qublog</groupId>
<artifactId>spring01_di</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
</project>
AccountServiceインターフェース:
package com.qublog.service;
//账户业务层接口
public interface AccountService {
//模拟保存账户
void saveAccount();
}
AccountServiceImplクラス:
package com.qublog.service.impl;
import com.qublog.service.AccountService;
import java.util.Date;
//账户的业务层实现类
public class AccountServiceImpl implements AccountService {
//如果是经常变化的数据,并不适用于注入的方式
private String name;
private Integer age;
private Date birthday;
public AccountServiceImpl(String name, Integer age, Date birthday) {
this.age = age;
this.name = name;
this.birthday = birthday;
}
public void saveAccount() {
System.out.println("service中的saveAccount方法执行了"+name+","+age+","+birthday);
}
}
bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 把对象的创建交给spring来管理 -->
<!-- 构造函数注入:
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签的属性
-->
<bean id="accountService" class="com.qublog.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="泰斯特"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
</beans>
クライアントクラス:
package com.qublog.ui;
import com.qublog.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//模拟一个表现层,用于调用业务层
public class Client {
public static void main(String[] args) {
//获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//根据id获取bean对象,下面两种方式都可以
AccountService as = (AccountService)ac.getBean("accountService");
as.saveAccount();
}
}
結果を印刷します。