Spring的狂神說筆記
Spring-Study
程式碼:https://github.com/Donkequan/Spring-Study
1. 簡介
-
SSH:Struct2 + Spring + Hibernate
-
SSM: SpringMVC + Spring + Mybatis
官網: https://spring.io/projects/spring-framework#overview
官方下載: https://repo.spring.io/release/org/springframework/spring/
GitHub:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
-
spring是開源的免費的容器。
-
spring是一個輕量級的,非入侵式的。
-
控制反轉(IOC),面向切面程式設計 (AOP)。
-
支援事務處理,對框架整合的支援。
總結:spring是一個輕量級的控制反轉(IOC)和麵向切面程式設計(AOP)的框架。
2.IOC理論
-
UserDao
-
UserDaoImp
-
UserSevice
-
UserServiceImp
在之前,使用者的需求可能會影響原來的程式碼。
使用一個set。
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
-
之前是主動建立物件,控制權在程式設計師手上。
-
使用set之後,是被動接受物件。
3. Hello Spring
pojo中
package com.hou.pojo;
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
resource種
test
import com.hou.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
public static void main(String[] args) {
//獲取spring上下文物件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我們的物件下能在都在spring·中管理了,我們要使用,直接取出來就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
bean = 物件 id = 變數名 class = new的物件 property 相當於給物件中的屬性設值
核心用set注入
第一個檔案中
4. IOC建立物件的方式
-
使用無參構造建立物件,預設。
-
使用有參構造
下標賦值
型別賦值(不建議使用)
<bean id="user" class="com.hou.pojo.User">
<constructor-arg type="java.lang.String" value="dong"/>
</bean>
直接通過引數名
<bean id="user" class="com.hou.pojo.User">
<constructor-arg name="name" value="hou"></constructor-arg>
</bean>
Spring類似於婚介網站!
你想不想要,物件都在裡面。註冊bean之後用不用被例項化。
5. Spring配置
別名
<bean id="user" class="com.hou.pojo.User">
<constructor-arg name="name" value="hou"></constructor-arg>
</bean>
<alias name="user" alias="user2aaa"/>
Bean的配置
-
id:bean的id識別符號
-
class:bean物件所對應的型別
-
name:別名,更高階,可以同時取多個別名。
import
一般用於團隊開發,它可以將多個配置檔案,匯入合併為一個
<import resource="beans.xml"/>
6. DI依賴注入
構造器注入
set方式注入(重點)
-
依賴:bean物件的建立依賴於容器
-
注入:bean物件中的所有屬性,由容器來注入
【環境搭建】
-
複雜型別
-
真實測試物件
package com.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> game;
private Properties infor;
private String wife;