目次
春の紹介
Spring は、エンタープライズレベルの開発を簡素化するために生まれたオープンソース フレームワークです。IOC (Inversion of Control) と AOP (Aspect-Oriented) を思想的核としており、制御層 SpringMVC、データ層 SpringData、サービス層トランザクション管理などの多くのテクノロジを提供し、多くのサードパーティ フレームワークを統合できます。Spring は多くの複雑なコードをエレガントかつ簡潔にし、コードの結合度を効果的に減らし、その後のプロジェクトのメンテナンス、アップグレード、拡張を大幅に容易にします。
Spring公式サイトアドレス:https://spring.io/
春の建築
Springフレームワークは機能別に複数のモジュールに分かれており、エンタープライズレベルのアプリケーション開発のあらゆるニーズに対応し、開発プロセス中に必要なモジュールを要件に応じて選択して使用することができます。
1. Core Container : Spring のコアモジュールであり、あらゆる機能の使用はこのモジュールから切り離すことができず、他のモジュールを構築するための基礎となります。
2.データ アクセス/統合: このモジュールは、データ永続化に対応する機能を提供します。
3. Web : このモジュールは、Web 開発に対応する機能を提供します。
4. AOP : アスペクト指向プログラミングの実装を提供します。
5.アスペクト: アスペクト指向プログラミング フレームワークである AspectJ フレームワークとの統合を提供します。
6.インストルメンテーション: 特定のアプリケーション サーバーで使用できるクラス ツールとクラス ローダーの実装のサポートを提供します。
7.メッセージング: Spring フレームワーク用のいくつかの基本的なメッセージング アプリケーションを統合します。
8.テスト: テスト フレームワークとの統合を提供します。
IOC_制御思想の逆転
IOC (Inversion of Control): プログラムはオブジェクトを作成する権利をフレームワークに渡します。以前の開発プロセスでは、オブジェクト インスタンスの作成は呼び出し元によって管理されており、コードは次のとおりです。
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"程序员","北京");
}
}
public class StudentService {
public Student findStudentById(int id){
// 此处就是调用者在创建对象
StudentDao studentDao = new StudentDaoImpl();
return studentDao.findById(1);
}
}
この書き方には次の 2 つの欠点があります。
1 リソースの無駄: StudentService がメソッドを呼び出すとオブジェクトが作成され、メソッドを呼び続けると大量の StudentDao オブジェクトが作成されます。
2 高度なコード結合: 開発に伴い、StudentDao のより完全な実装クラス StudentDaoImpl2 を作成したとします。StudentDaoImpl2 を StudentService で使用したい場合は、ソース コードを変更する必要があります。
IOCの考え方は、オブジェクトを作成する権利をフレームワークに渡すというもので、フレームワークはオブジェクトの作成とオブジェクトの使用の割り当てを支援し、制御権はプログラムコードからフレームワークに移され、制御権は逆転されます。これがスプリングのIOCのアイデアだ。IOC のアイデアは、上記 2 つの問題を完全に解決します。
IOC_カスタム オブジェクト コンテナ
次に、コードを使用して IOC のアイデアをシミュレートします。コレクション コンテナを作成するには、まずオブジェクトを作成してコンテナに置きます。オブジェクトを使用する必要がある場合は、再作成せずにコンテナからオブジェクトを取得するだけで済みます。このとき、コンテナは物体。
エンティティクラスの作成
public class Student {
private int id;
private String name;
private String address;
// 省略getter/setter/构造方法/tostring
}
Daoインターフェースと実装クラスを作成する
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"程序员","北京");
}
}
public class StudentDaoImpl2 implements StudentDao{
@Override
public Student findById(int id) {
// 模拟根据id查询学生
System.out.println("新方法!!!");
return new Student(1,"程序员","北京");
}
}
管理対象オブジェクトを定義する構成ファイル bean.properties を作成します。
studentDao=com.tong.dao.StudentDaoImpl
コンテナ管理クラスを作成します。このクラスは、クラスのロード時に構成ファイルを読み取り、構成ファイルに構成されているすべてのオブジェクトを作成してコンテナに配置します。
public class Container {
static Map<String,Object> map = new HashMap();
static {
// 读取配置文件
InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 遍历配置文件的所有配置
Enumeration<Object> keys = properties.keys();
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
String value = properties.getProperty(key);
try {
// 创建对象
Object o = Class.forName(value).newInstance();
// 将对象放入集合中
map.put(key,o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 从容器中获取对象
public static Object getBean(String key){
return map.get(key);
}
}
Dao オブジェクトの呼び出し元 StudentService を作成します。
public class StudentService {
public Student findStudentById(int id)
{
// 从容器中获取对象
StudentDao studentDao = (StudentDao) Container.getBean("studentDao");
System.out.println(studentDao.hashCode());
return studentDao.findById(id);
}
}
テスト学生サービス
public class Test {
public static void main(String[] args)
{
StudentService studentService = new StudentService();
System.out.println(studentService.findStudentById(1));
System.out.println(studentService.findStudentById(1));
}
}
IOC_Spring は IOC を実装します
次に、Spring を使用して IOC を実装します。Spring 内にはオブジェクトを管理するコンテナもあります。
Maven プロジェクトを作成し、依存関係を導入する
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
POJOクラス、Daoクラス、インターフェースを作成する
public class Student {
private int id;
private String name;
private String address;
// 省略getter/setter/构造方法/tostring
}
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"程序员","北京");
}
}
XML 構成ファイルを作成し、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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
</beans>
このテストでは、Spring コンテナーからオブジェクトをフェッチします。
public class TestContainer {
@Test
public void t1(){
// 创建Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 从容器获取对象
StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
System.out.println(studentDao1.hashCode());
System.out.println(studentDao2.hashCode());
System.out.println(studentDao1.findById(1));
}
}
IOC_Spring コンテナ タイプ
コンテナインターフェース
1. BeanFactory: BeanFactory は、Bean オブジェクトを管理できる Spring コンテナーの最上位インターフェースです。
2. ApplicationContext: ApplicationContext は BeanFactory のサブインターフェースです。BeanFactory のすべての機能を継承するだけでなく、国際化、リソース アクセス、イベント伝播の優れたサポートも追加されています。
ApplicationContext には、一般的に使用される次の 3 つの実装クラスがあります。
コンテナ実装クラス
1. ClassPathXmlApplicationContext: このクラスはプロジェクトから構成ファイルを読み取ることができます
2. FileSystemXmlApplicationContext: このクラスはディスクから構成ファイルを読み取ります。
3. AnnotationConfigApplicationContext: このクラスを使用すると、構成ファイルは読み取られませんが、注釈が読み取られます。
@Test
public void t2(){
// 创建spring容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\a\\IdeaProjects\\spring_demo\\src\\main\\resources\\bean.xml");
// 从容器中获取对象
StudentDao userDao = (StudentDao)ac.getBean("studentDao");
System.out.println(userDao);
System.out.println(userDao.findById(1));
}
IOC_objects の作成方法
Spring は Bean の作成を支援します。では、Bean を作成するために下部でどのメソッドが呼び出されるでしょうか?
コンストラクターを使用する
デフォルトでは、Spring はクラスの空のパラメーター コンストラクターを使用して Bean を作成します。
// 假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao{
public StudentDaoImpl(int a){}
@Override
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"程序员","北京");
}
}
ファクトリクラスのメソッドを使用する
Spring はファクトリ クラスのメソッドを呼び出して Bean を作成できます。
1. オブジェクトを作成するためのメソッドを提供するファクトリ クラスを作成します。
public class StudentDaoFactory {
public StudentDao getStudentDao(){
return new StudentDaoImpl(1);
}
}
2 設定ファイルで Bean の作成方法をファクトリ メソッドとして設定します。
<!-- id:工厂对象的id,class:工厂类 -->
<bean id="studentDaoFactory" class="com.tong.dao.StudentDaoFactory"></bean>
<!-- id:bean对象的id,factory-bean:工厂对象 的id,factory-method:工厂方法 -->
<bean id="studentDao" factorybean="studentDaoFactory" factory-method="getStudentDao"></bean>
3つのテスト
ファクトリクラスの静的メソッドを使用する
Spring はファクトリ クラスの静的メソッドを呼び出して Bean を作成できます。
1 オブジェクトを作成するための静的メソッドを提供するファクトリ クラスを作成します。
public class StudentDaoFactory2 {
public static StudentDao getStudentDao2() {
return new StudentDaoImpl();
}
}
2 構成ファイルで Bean を作成するメソッドをファクトリー静的メソッドとして構成します。
<!-- id:bean的id class:工厂全类名 factory-method:工厂静态方法 -->
<bean id="studentDao" class="com.tong.dao.StudentDaoFactory2" factory-method="getStudentDao2"></bean>
3つのテスト