学习Spring第一天

学习Spring第一天

1. Spring概述

1.1 简介

  • Spring : 春天 —>给软件行业带来了春天
  • 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
  • 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
  • 很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
  • Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术

Spring官网

Spring官方下载

GitHub

Spring Web MVC和Spring-JDBC的pom配置文件:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

1.2 优点

  • Spring是一个开源免费的框架 , 容器 .

  • Spring是一个轻量级的框架 , 非侵入式的 .

  • 控制反转 IoC , 面向切面 Aop

  • 对事物的支持 , 对框架的支持

一句话概括:Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

1.3 组成

  • 核心容器
  • Spring 上下文
  • Spring AOP
  • Spring DAO
  • Spring ORM
  • Spring Web 模块
  • Spring MVC 框架

2. IoC(控制反转)理论推导

2.1 分析实现

  1. 先写一个UserDao接口
public interface UserDao {
    void getUser();
}
  1. 再写Dao的实现类
public class UserDaoImpl implements UserDao{
    public void getUser(){
        System.out.println("默认获取用户的数据");
    }
}
  1. 然后写UserService的接口
public interface UserService {
    void getUser();
}
  1. 最后写Service的实现类
public class UserServiceImpl implements UserService{
    private UserDao userDao;
    public void getUser(){
        userDao.getUser();
    }
}
  1. 测试
@Test
public void test(){
	UserService service = new UserServiceImpl();
	service.getUser();
}

改良:我们使用一个Set接口实现

//利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

改良后测试增加:

((UserServiceImpl)userService).setUserDao(new UserDaoImpl());

2.2 IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认 为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系 完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为 所谓控制反转就是:获得依赖对象的方式反转了。

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解, 新版本的Spring也可以零配置实现IoC。

3. HelloSpring

3.1 导入jar包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.7.RELEASE</version>
 </dependency>

3.2 编写代码

  1. 编写一个Hello实体类
   package com.zhang.pojo;
   
   /**
    * @author feige
    * @create 2021-09-24 8:55
    */
   public class Hello {
       private String str;
   
       public String getStr() {
           return str;
       }
   
       public void setStr(String str) {
           this.str = str;
       }
   
       @Override
       public String toString() {
           return "Hello{" +
                   "str='" + str + '\'' +
                   '}';
       }
   }
 
  1. 编写Spring文件,命名为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"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd">
   
       <!--使用spring来创建对象,在spring这些都称为bean
           类型 变量名 = new 类型();
           Hello hello = new Hello();
           id = 变量名
           class = new 的对象
           property 相当于给对象中的属性设置一个值
           -->
       <bean id="hello" class="com.zhang.pojo.Hello">
           <property name="str" value="Spring"/>
       </bean>
   </beans>
  1. 测试
import com.zhang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author feige
 * @create 2021-09-24 8:59
 */
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());
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lv0znB7N-1632473600905)(C:\Users\12545\AppData\Roaming\Typora\typora-user-images\image-20210924153033310.png)]

3.3 思考

  • Hello的对象hello是有Spring创建的
  • hello的属性是有Spring容器设置的
  • 依赖注入:利用set方法进行注入

3.4 修改案例

在之前的案例中新增一个Spring配置文件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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="mysqlImpl" class="com.zhang.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.zhang.dao.UserDaoOracleImpl"/>
    <bean id="userServiceImpl" class="com.zhang.service.UserServiceImpl">
        <property name="userDao" ref="mysqlImpl"/>
        <!--
     ref:引用spring容器中创建好的对象
     value:具体的值,基本数据类型
     -->
    </bean>

</beans>

测试

import com.zhang.dao.UserDaoImpl;
import com.zhang.dao.UserDaoMysqlImpl;
import com.zhang.dao.UserDaoOracleImpl;
import com.zhang.dao.UserDaoSqlServerImpl;
import com.zhang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author feige
 * @create 2021-09-24 8:22
 */
public class MyTest {

    public static void main(String[] args) {

        //获取ApplicationContext;拿到spring的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //容器在手天下我有
        UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
        serviceImpl.getUser();
    }
}

4. IOC创建对象

4.1 通过无参构造方法创建

  1. User.java
package com.zhang.pojo;
   
   /**
    * @author feige
    * @create 2021-09-24 9:29
    */
   public class User {
       private String name;
   
       public User() {
           System.out.println("user无参构造");
       }
   
       public String getName() {
           return name;
       }
   
       public void setName(String name) {
           this.name = name;
       }
       public void show(){
           System.out.println("name = " + name);
       }
   }
  1. beans.xml
 <bean id="user" class="com.zhang.pojo.User">
           <property name="name" value="飞哥"/>
   </bean>
  1. 测试类
@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }

在这里插入图片描述

4.2 通过有参构造来创建

  1. UserT.java
 package com.zhang.pojo;
   
   /**
    * @author feige
    * @create 2021-09-24 10:02
    */
   public class UserT {
       private String name;
   
       public UserT(String name) {
           this.name = name;
       }
   
       public String getName() {
           return name;
       }
   
       public void setName(String name) {
           this.name = name;
       }
       public void show(){
           System.out.println("name = " + name);
       }
   }
  1. beans.xml的三种编写方式
 <!--第一种下标赋值-->
 <bean id="userT" class="com.zhang.pojo.UserT">
       <constructor-arg index="0" value="飞哥"/>
 </bean>
<bean id="userT" class="com.zhang.pojo.UserT">
        <!--name指参数名-->   
        <constructor-arg name="name" value="飞哥"/>
</bean>
<bean id="userT" class="com.zhang.pojo.UserT">
        <constructor-arg type="java.lang.String" value="飞哥"/>
</bean>
  1. 测试
@Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserT user = (UserT) context.getBean("userT");
        user.show();
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cAa15HZl-1632473600922)(C:\Users\12545\AppData\Roaming\Typora\typora-user-images\image-20210924155510433.png)]

5.Spring配置

5.1 别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
    <alias name="userT" alias="userNew"/>

测试

 @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserT user = (UserT) context.getBean("userNew");
        user.show();
    }

5.2 Bean的配置

<!--bean就是java对象,由Spring创建和管理-->
<!--
id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
如果配置id,又配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.zhang.pojo.Hello">
		<property name="name" value="Spring"/>
</bean>

5.3 import

团队合作通过import来实现

创建beans.xml和applicationContext.xml

在applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="beans.xml"/>

</beans>

6. 依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .

6.1 构造器注入

见4.2中

6.2 set注入(重点)

测试pojo类:

Address.java

package com.zhang.pojo;

/**
 * @author feige
 * @create 2021-09-24 10:29
 */
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }

}

Student.java

package com.zhang.pojo;

import java.util.*;

/**
 * @author feige
 * @create 2021-09-24 10:28
 */
public class Student {
    private String name;
    private Address address;
    private String[] book;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private Properties info;
    private String wife;


    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[] getBook() {
        return book;
    }

    public void setBook(String[] book) {
        this.book = book;
    }

    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;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", book=" + Arrays.toString(book) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", info=" + info +
                ", wife='" + wife + '\'' +
                '}';
    }
}
  1. 常量注入
<bean id="student" class="com.zhang.pojo.Student">
<!--第一种:普通值注入,value-->
        <property name="name" value="飞哥"/>
</bean>
  1. Bean注入

注意点:这里的值是一个引用,ref

<bean id="address" class="com.zhang.pojo.Address">
        <property name="address" value="安徽"/>
    </bean>
<bean id="student" class="com.zhang.pojo.Student">
<!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
</bean>
  1. 数组注入
<bean id="student" class="com.zhang.pojo.Student">
<!--数组注入-->
        <property name="book">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>三国演义</value>
                <value>水浒传</value>
            </array>
        </property>
</bean>
  1. List注入
    <bean id="student" class="com.zhang.pojo.Student">
<!--List注入-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>踢足球</value>
                <value>看电影</value>
            </list>
        </property>
</bean>
  1. Map注入
   <bean id="student" class="com.zhang.pojo.Student">
<!--Map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="1234567890"/>
                <entry key="银行卡" value="2423435346"/>
            </map>
        </property>
</bean>
  1. set注入
	<bean id="student" class="com.zhang.pojo.Student">
<!-- Set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>DNF</value>
                <value>BOB</value>
            </set>
        </property>
</bean>
  1. Null注入
    <bean id="student" class="com.zhang.pojo.Student">
<!-- null-->
        <property name="wife">
            <null/>
        </property>
</bean>
  1. Properties注入
   <bean id="student" class="com.zhang.pojo.Student">
<!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">0001</prop>
                <prop key="性别"></prop>
            </props>
        </property>
    </bean>

测试结果:

Student{name='飞哥', address=Address{address='安徽'}, book=[红楼梦, 西游记, 三国演义, 水浒传], hobbies=[听歌, 敲代码, 踢足球, 看电影], card={身份证=1234567890, 银行卡=2423435346}, games=[LOL, DNF, BOB], info={学号=0001, 性别=男}, wife='null'}

6.3拓展注入实现

  1. P命名空间注入

User.java:【注意:没有构造器】

package com.zhang.pojo;

/**
 * @author feige
 * @create 2021-09-24 14:12
 */
public class User {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

P命名空间注入:需要在头文件中加入约束条件

导入约束:xmlns:p="http://www.springframework.org/schema/p"
   
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.zhang.pojo.User" p:name="飞哥" p:age="24"/>

测试:

 @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user);
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8KvZ4nyH-1632473600928)(C:\Users\12545\AppData\Roaming\Typora\typora-user-images\image-20210924164849439.png)]

  1. c命名空间注入

User.java:【注意:有构造器】

package com.zhang.pojo;

/**
 * @author feige
 * @create 2021-09-24 14:12
 */
public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

c命名空间注入:需要在头文件中加入约束文件

导入约束:xmlns:c="http://www.springframework.org/schema/c"

<!--c命名空间注入,通过构造器注入:construct-->
<bean id="user2" class="com.zhang.pojo.User" c:age="23" c:name="小青" scope="singleton"/>

测试:

 @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2", User.class);
        System.out.println(user);
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jXCt5VGu-1632473600931)(C:\Users\12545\AppData\Roaming\Typora\typora-user-images\image-20210924164916985.png)]

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值