Spring系列01——初识Spring框架



Spring系列01——初识Spring框架

如果你是初学框架的小白,那么这篇可能会适合你,会带你大致了解怎么简单使用Spring框架。而且这会成为一个系列,不定时更新。

什么是Spring框架?

Spring(Spring Framework)框架是轻量级,方便解耦,简化开发。Spring框架有两个核心的点,一个是IoC(控制反转),一个是AOP面向切面。(实际上Spring框架有很多东西,我们初学掌握IoCAOP事务JdbcTemplate即可)


IoC(Inversion Of Control)( IoC 也称为依赖注入 (DI)): IoC即控制反转,把对象的创建和对象之间的调用过程,交给`Spring`容器进行管理;控制即当前对象对内部成员的控制权,反转指的是对象的控制权由其他(第三方容器管理)其实使用 IoC的目的是为了解耦(没有什么加上一层解决不了的)
AOP:在原有的基础上增强代码的实用性(后续文章会讲)

至于为什么要学Spring框架,它有什么用,有什么优点?可以自行百度百科(已经讲得很清楚),链接在下面

https://baike.baidu.com/item/spring%E6%A1%86%E6%9E%B6/2853288?fr=aladdin

Spring有很多模块,所以要使用哪个模块就对应导入哪个模块的包
mk使用Spring,导入下面这个依赖即可,会自动集成该模块所需要的依赖

<!--要使用spring,使用下面整个=-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.7</version>
</dependency>

Spring操作Bean管理

什么是Bean :简单笼统的说就是一个类,一个可复用的类;BeanSpring中的作用就像ObjectOOP的意义一样,没有对象就没有面向对象编程,在Spring中没有Bean也就没有了Spring存在的意义。Spring操作Bean有基于配置文件(也就是xml文件)也有基于注解。这里着重讲第二种

简单的 IoC实例

package com.cjjy.pojo;
public class SpringDemo {
    public Cat cat;
    public Dog dog;
    public String name;
	//省略了set、get方法
}
package com.cjjy.pojo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {

    public static void main(String[] args) {
        //加载spring配置文件
        /*
        	Spring提供IoC两种实现方式(两个接口)一个BeanFactory:IoC容器基本实现,是Spring内部的使用接口,不提供开发人员进行处理(一般不使用这个);常用的是这个ApplicationContext,它是BeanFactory接口的子接口,提供更多的功能。不过BeanFactory是加载配置文件的时候不会创建对象,在获取的时候才会。ApplicationContext相反,加载配置文件的时候会把在配置文件对象进行创建(一般是趁服务器后启动时加载对象,而不是用到的时候创建对象,所以一般都是使用这个ApplicationContext)
        	ApplicationContext接口有实现类
        		FileSystemXmlApplicationContext:这个是加载文件用的是文件所在的系统盘符路径
        		ClassPathXmlApplicationContext:这个则是类路径
        */
        //容器中对象的创建在容器创建完成的时候就已经创建好了
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        //获取配置创建的对象
        SpringDemo springDemo = context.getBean("springDemo", SpringDemo.class);
        springDemo.setName("张三");
        System.out.println(springDemo.getName()
        );
    }
}

把对象的创建和对象之间的调用过程,交给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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--配置SpringDemo对象创建
			bean标签表示可以注册一个组件(对象、类)
			id:唯一标识(这里还有一个name属性(也是别名),本质跟id差不多,name属性是早期使用的,可以添加特殊字符,且name属性可以同时取多个别名)
			class属性:类的全路径(也就是整个包名)
			import:用户团队开发使用,可以配置多个文件,导入合并一个
		这种方式默认调用的是无参的构造方法,如果类里面有有参的构造方法就会报错
	-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo"></bean>
    
</beans>

然后下面是属性注入

属性注入

xml 配置中,属性的注入存在多种方式。属性注入又分为两种,一种通过set注入,另一种是使用有参的构造进行注入(下面这种是基于set方式注入)

<?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">
        
    <!--这种是基于set方式注入-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <property name="name" value="张三"></property>
    </bean>
    
    <!--这种是基于构造器方式进行注入-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <!--可以通过索引(index)来获取构造方法的参数,默认0是第一个参数,以此类推,然后赋值;name也可以省略不写,严格按照构造器参数的位置-->
        <!-- <constructor-arg name="name" value="张四"></constructor-arg>-->
        <constructor-arg index="0" value="张四"></constructor-arg>
    </bean>
</beans>

也可以使用c标签和p标签来进行属性注入,为什么要使用p标签?

名称空间:在xml配置文件中名称空间是用来防止标签重复的,举个例子,比如xml配置中,book有书名也有作者名,同样是name,为了防止引用失败,所以就有了我们的p命令空间。带前缀的标签 <c:forEach> <jsp:forward>

这种是基于set方式注入,可以简化,也可以使用p标签来给属性赋值(p标签本质就是通过set注入)

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo" p:name="张三"></bean>
</beans>

特殊符号和null值注入

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--null值注入-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <property name="name">
            <!--设置空值,这里提一下,复杂赋值最好拆开来写-->
            <null/>
        </property>
    </bean>
    
    <!--特殊符号-->
     <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <!--属性含特殊符号,要么用转义字符要么把值写到<![CDATA[]]>里面去-->
        <!--<property name="name" value="&lt;&gt;"></property>-->
        <property name="name" >
            <!--可以分开写-->
            <value><![CDATA[<<帅哥>>]]></value>
        </property>
    </bean>
</beans>

外部bean和级联赋值

通过外部bean

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <!--
			name:属性名称
			ref属性:创建cat对象bean标签id-->
        <property name="cat" ref="cat"></property>
    </bean>

    <!--外部创建对象,然后通过ref引入-->
    <bean id="cat" class="com.cjjy.pojo.Cat"></bean>
</beans>

级联赋值

级联赋值:级联就是比如一个类的属性引用了另一个类,另一个类的属性相对应第一个类来说就是级联

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--内部bean-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <!--设置普通属性-->
        <property name="name" value="张三"></property>
        <!--设置对象类型属性	-->
        <property name="cat">
            <!--这种方式只能是内部bean自己使用,不能被外部获取id-->
            <bean id="cat" class="com.cjjy.pojo.Cat">
                <property name="name" value="花花与山猫"></property>
            </bean>
        </property>
    </bean>
</beans>
<!--下面这种是级联赋值-->
<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <property name="name" value="张三"></property>
        <!--级联赋值-->
        <property name="cat" ref="cat"></property>
    </bean>

    <bean id="cat" class="com.cjjy.pojo.Cat">
        <property name="name" value="花花与山猫"></property>
    </bean>

</beans>

还有一种写法,生成某个对象的get方法然后去获取属性

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <property name="name" value="张三"></property>
        <!--级联赋值-->
        <property name="cat" ref="cat"></property>
        <!--com.cjjy.pojo.SpringDemo这个类内部Cat对象必须有要有getCat()方法,否则报错-->
        <property name="cat.name" value="内部的山猫与花花"></property>
    </bean>

    <bean id="cat" class="com.cjjy.pojo.Cat">
        <property name="name" value="花花与山猫"></property>
    </bean>

</beans>
package com.cjjy.pojo;
public class Cat {

    private String name;
	//省略了set、get方法
}
package com.cjjy.pojo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        //创建对象
        SpringDemo springDemo = context.getBean("springDemo", SpringDemo.class);
        System.out.println(springDemo.cat.getName());//输出结果:花花与山猫
    }
}

对于某一个类型属性通用性较高的情况下,可以单独的提取出来,给需要的bean进行引用。

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        https://www.springframework.org/schema/util/spring-util.xsd">


    <!--使用util标签完成list集合注入提取-->
    <util:list id="utilTest">
        <value>java语言</value>
        <value>golang语言</value>
        <value>c语言</value>
    </util:list>

    <!--使用list集合类型属性注入使用-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">
        <property name="list" ref="utilTest"></property>
    </bean>

</beans>
    package com.cjjy.pojo;
    import java.util.List;
    public class SpringDemo {
        private List<String> list;
        public List<String> getList() {
            return list;
        }
        public void setList(List<String> list) {
            this.list = list;
        }
        public void showCollection(){
            System.out.println(list);
        }
    }

bean的作用域

创建bean实例的时候,可以是单实例对象(默认是单实例对象,简单来说就是无论怎么getBean()获取的都是同一个对象),bean也有作用域,也可以通过设置变成多实例对象

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        https://www.springframework.org/schema/util/spring-util.xsd">

    <!--单实例:只有一个对象;多实例:每次都建一个新对象
			在spring配置文件bean标签中有个属性scope用来设置bean的作用域
			singleton:表示单实例对象;prototype:表示多实例对象
			设置scope值是singleton的时候,加载spring配置文件时候就会创建单实例对象(ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");)
			设置scope值是prototype的时候,不是在加载spring配置文件时候创建对象,在调用getBean()方法的时候创建多实例对象(原型模式(每次从容器中get的时候,都会产生一个新对象))
	-->
    <!--singleton:表示单实例对象-->
    <bean id="myTest" class="com.cjjy.pojo.MyTest" scope="singleton"></bean>
    <!--prototype:表示多实例对象-->
    <bean id="myTest" class="com.cjjy.pojo.MyTest" scope="prototype"></bean>

</beans>

其他属性注入

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--集合类型属性注入-->
    <bean id="springDemo" class="com.cjjy.pojo.SpringDemo">

        <!--数组类型属性注入-->
        <property name="str">
            <array>
                <value>张三</value>
                <value>李四</value>
                <value>李武</value>
            </array>

            <!--list或者array标签都可以-->
<!--            <list>
                &lt;!&ndash;添加多个参数&ndash;&gt;
                <value>张三</value>
                <value>李四</value>
                <value>李武</value>
            </list>-->
        </property>
        <property name="list">
            <list>
                <value>张三老婆</value>
                <value>李四老婆</value>
                <value>李武老婆</value>
            </list>
        </property>

        <!--map类型属性注入-->
        <property name="map">
            <!--map=new LinkedHashMap<>();-->
            <map>
                <entry key="姓名" value="张三"></entry>
                <entry key="年轻" value="23"></entry>
                <entry key="性别" value=""></entry>
            </map>
        </property>
        <property name="set">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>

        <!--注入list集合类型,值是对象-->
        <property name="catVarieties">
            <list>
                <!--引入对象-->
                <ref bean="cat1"></ref>
                <ref bean="cat2"></ref>
            </list>
        </property>
    </bean>

    <!--创建多个cat对象-->
    <bean id="cat1" class="com.cjjy.pojo.Cat">
        <property name="name" value="咖啡猫"></property>
    </bean>
    <bean id="cat2" class="com.cjjy.pojo.Cat">
        <property name="name" value="奶猫"></property>
    </bean>
</beans>
    package com.cjjy.pojo;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    public class SpringDemo {
        private Cat cat;
        private String[] str;
        private List<String> list;
        private Map<String,String> map;
       	private Set<String> set;
        private  List<Cat> catVarieties;
		//省略了set、get方法
        public void showCollection(){
            System.out.println(Arrays.toString(str));
            System.out.println(list);
            System.out.println(map);
            System.out.println(set);
           System.out.println(catVarieties);
        }
    }
package com.cjjy.pojo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test(){
       ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
       //创建对象
       SpringDemo springDemo = context.getBean("springDemo", SpringDemo.class);
       springDemo.showCollection();
    }
}
/*
[张三, 李四, 李武]
[张三老婆, 李四老婆, 李武老婆]
{姓名=张三, 年轻=23, 性别=男}
[MySQL, Redis]
[Cat{name='咖啡猫'}, Cat{name='奶猫'}]
*/

更多注入的方式请查官方文档

Spring core文档使用地址:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值