Spring快速入门笔记

一、概念部分(初学者一定要先弄清楚的一些概念)
1.什么是Spring?
Spring是一个开发框架,不管是Ioc还是Aop,其主要目的都是为了解耦项目。
2.什么是Ioc?有什么用?
Ioc翻译为控制反转,意思是将对象资源的控制权由用户控制交由Spring控制。
具体一点就是,之前写代码都要程序员使用关键字new出来。带来的问题就是,类与类之间耦合严重。比如“Person st = new Person()” 如果我需要将这个“Person”类替换成“Student”类,我就得把项目所有的“new Person” 改为 “new Student”,这非常麻烦。而使用Spring框架就可以直接在其配置文件里面进行修改资源名,就能完成这一操作。
3.什么是DI?
DI翻译为依赖注入,实际就是Ioc从不同角度来看而改变了其称呼。其本质是一件事,Ioc是站在Spring角度看用户(我Spring从用户手中取得了new 的控制权),DI是站在用户角度看Spring(你Spring需要我用户注入数据)。
4.Spring怎么进行的解耦?
Spring使用了 工厂模式+配置文件 的方式进行解耦。工厂负责制造资源,配置文件负责资源的分发。造成资源耦合与工厂,工厂耦合于配置文件,配置文件又耦合于配置文件。从而实现了资源与用户之间的隔离,而配置文件与工厂的耦合相对好处理。

二、使用Spring
1.第一个Spring案例。
①你需要导入Spring的jar包,最好直接使用maven进行坐标导入。
②创建一个实体类“Spring_test.java”。
③创建资源文件“applicationContext.xml”,并引入头约束文件。
④引入实体类的资源信息。
⑤创建代理类并读取配置文件,利用代理类生成需要使用的实体类。
⑥利用实体类调用方法
实体类 Spring_test.java

public class Spring_test {
    public static void testFunction(){
        System.out.println("此方法运行了");
    }
">

配置文件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"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       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
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
">
<!--    上面都是xml的约束文件         -->
<!--    配置资源信息,id属性用于调用时的映射,class属性用户寻找资源-->
    <bean id="test" class="全限定类名"/>
</beans>

主函数TestMethod.java

//Spring入门案例
public class TestMethod {
    public static void main(String[] args) {
        //创建ApplicationContext对象并读取配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从对象中调用getBean方法以配置文件中的id名为检索信息。获取获取beam对象,需要强转
        Spring_test test = (Spring_test) ctx.getBean("test");
        //利用test调用方法,控制台输出“此方法运行了”
        test.testFuntion();
    }
}

三、Spring常用注解
1.@Component(“calssId”)
位置:类名上方
作用:扫描这个类,将这个类纳入Spring容器内,id为键值当作查找条件。

2.@Scope(“prototype”)
位置:类名上方
作用:切换多例模式,还有一个singleton的值。为单例模式,但系统默认单例模式。

3.@PostConstruct
位置:初始化方法上方
作用:标记该类的初始化方法

4.@PreDestory
位置:销毁方法上方
作用:标记该类的销毁方法

5.@Bean(“beanName”)
位置:方法名上方
作用:设置该方法的返回值位置Spring管理的的bean,经常用于获取第三方资源。
注意:该注解静态方法和非静态均可使用,

6.@Value
位置:属性上方或方法上方
作用:设置对象的值,或对方法传递参数。
注意:仅支持非引用类型,支持properties文件的注入,支持EL表达式。

7.@AutoWired、@Quqlifier(className)
位置:方法名上方或类上方
作用:设置对应属性的对象或者对方法进行引用类型传参,@AutoWired自动装配,@Quqlifier(“calssName”)按照bean名字装配。

8.@Primary
位置:类名上方
作用:设置类对应的bean,提高装配优先度
说明:@Autowired默认按类型装配,当出现想同的bean,使用@Primary可设置优先装配。另外两个及以上将导致无效。

9.@PeopertySource(“fileName.properties”)
位置:类名上方
作用:指定properties文件的位置
注意:不支持通配符*,若要添加多个格式如下@PeopertySource({“fileName1.properties”},{“fileName2.properties”})

10.@Configuration、@ComponentScan
位置:类名上方
作用:设置当前类为Spring核心配置加载类

四、spring的事务操作(aop抽成)
TxAdvice.java

public class TxAdvice {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable {
        //创建事务管理器
        DataSourceTransactionManager datm = new DataSourceTransactionManager();
        //给事务管理器添加数据资源
        datm.setDataSource(dataSource);
        //创建事务定义对象
        DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
        //创建事务状态对象
        TransactionStatus ts = datm.getTransaction(dt);
        // 创建事务对象 用于控制事务

        Object ret = pjp.proceed();

        // 提交事务
        datm.commit(ts);
        return ret;
    }

配置文件applicationContext.xml内容

    <bean id="txAdvice" class="com.aop.TxAdvice" >
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    aop配置-->
    <aop:config>
    <!--    aop的切点配置-->
        <aop:pointcut id="pt" expression="execution(* *..transfer(..))"/>
        <!--    aop的切面配置-->
        <aop:aspect ref="txAdvice">
        <!--    aop环绕方式以及指定方法-->
            <aop:around method="transactionManager" pointcut-ref="pt"/>
        </aop:aspect>
    </aop:config>

五、Spring的xml标签属性

5.1)bean

  • 名称:bean

  • 类型:标签

  • 归属:beans标签

  • 作用:定义spring中的资源,受此标签定义的资源将受到spring控制

  • 格式:

    <beans>
    	<bean />
    </beans>
    
  • 基本属性:

    <bean id="beanId" name="beanName1,beanName2" class="ClassName"></bean>
    

    ​ id:bean的名称,通过id值获取bean

    ​ class:bean的类型

    ​ name:bean的名称,可以通过name值获取bean,用于多人配合时给bean起别名

5.2)bean属性scope

  • 名称:scope

  • 类型:属性

  • 归属:bean标签

  • 作用:定义bean的作用范围

  • 格式:

    <bean scope="singleton"></bean>
    
  • 取值:

    • singleton:设定创建出的对象保存在spring容器中,是一个单例的对象
    • prototype:设定创建出的对象保存在spring容器中,是一个非单例的对象
    • request、session、application、 websocket :设定创建出的对象放置在web容器对应的位置

5.3)bean生命周期

  • 名称:init-method,destroy-method

  • 类型:属性

  • 归属:bean标签

  • 作用:定义bean对象在初始化或销毁时完成的工作

  • 格式:

    <bean init-method="init" destroy-method="destroy></bean>
    
  • 取值:bean对应的类中对应的具体方法名

  • 注意事项:

    • 当scope=“singleton”时,spring容器中有且仅有一个对象,init方法在创建容器时仅执行一次

    • 当scope=“prototype”时,spring容器要创建同一类型的多个对象,init方法在每个对象创建时均执行一次

    • 当scope=“singleton”时,关闭容器会导致bean实例的销毁,调用destroy方法一次

    • 当scope=“prototype”时,对象的销毁由垃圾回收机制gc()控制,destroy方法将不会被执行

5.4)bean对象创建方式(了解)

(1)factory-bean

  • 名称:factory-bean

  • 类型:属性

  • 归属:bean标签

  • 作用:定义bean对象创建方式,使用静态工厂的形式创建bean,兼容早期遗留系统的升级工作

  • 格式:

    <bean class="FactoryClassName" factory-method="factoryMethodName"></bean>
    
  • 取值:工厂bean中用于获取对象的静态方法名

  • 注意事项:

    • class属性必须配置成静态工厂的类名

(2)factory-bean,factory-method

  • 名称:factory-bean,factory-method

  • 类型:属性

  • 归属:bean标签

  • 作用:定义bean对象创建方式,使用实例工厂的形式创建bean,兼容早期遗留系统的升级工作

  • 格式:

    <bean factory-bean="factoryBeanId" factory-method="factoryMethodName"></bean>
    
  • 取值:工厂bean中用于获取对象的实例方法名

  • 注意事项:

    • 使用实例工厂创建bean首先需要将实例工厂配置bean,交由spring进行管理

    • factory-bean是实例工厂的beanId

程序的方式称为注入

5.5)set注入(主流)

  • 名称:property

  • 类型:标签

  • 归属:bean标签

  • 作用:使用set方法的形式为bean提供资源

  • 格式:

    <bean>
    	<property />
    </bean>
    
  • 基本属性:

    <property name="propertyName" value="propertyValue" ref="beanId"/>
    

​ name:对应bean中的属性名,要求该属性必须提供可访问的set方法(严格规范为此名称是set方法对应名称)

​ value:设定非引用类型属性对应的值,不能与ref同时使用

​ ref:设定引用类型属性对应bean的id ,不能与value同时使用

  • 注意:一个bean可以有多个property标签

5.6)构造器注入(了解)

  • 名称:constructor-arg

  • 类型:标签

  • 归属:bean标签

  • 作用:使用构造方法的形式为bean提供资源,兼容早期遗留系统的升级工作

  • 格式:

    <bean>
    	<constructor-arg />
    </bean>
    
  • 基本属性:

    <constructor-arg name="argsName" value="argsValue />
    

​ name:对应bean中的构造方法所携带的参数名

​ value:设定非引用类型构造方法参数对应的值,不能与ref同时使用

其他属性:

<constructor-arg index="arg-index" type="arg-type" ref="beanId"/>

​ ref:设定引用类型构造方法参数对应bean的id ,不能与value同时使用

​ type :设定构造方法参数的类型,用于按类型匹配参数或进行类型校验

​ index :设定构造方法参数的位置,用于按位置匹配参数,参数index值从0开始计数

  • 注意:一个bean可以有多个constructor-arg标签

5.7)集合类型数据注入

  • 名称:array,list,set,map,props

  • 类型:标签

  • 归属:property标签 或 constructor-arg标签

  • 作用:注入集合数据类型属性

  • 格式:

    <property>
    	<list></list>
    </property>
    

(1)集合类型数据注入——list

<property name="al">
    <list>
        <value>itheima</value>
        <value>66666</value>
    </list>
</property>

(2)集合类型数据注入——props

<property name="properties">
    <props>
        <prop key="name">itheima666</prop>
        <prop key="value">666666</prop>
    </props>
</property>

(3)集合类型数据注入——array (了解)

<property name="arr">
    <array>
        <value>123456</value>
        <value>66666</value>
    </array>
</property>

(4)集合类型数据注入——set(了解)

 <property name="hs">
     <set>
         <value>itheima</value>
         <value>66666</value>
     </set>
</property>

(5)集合类型数据注入——map(了解)

<property name="hm">
    <map>
        <entry key="name" value="itheima66666"/>
        <entry key="value" value="6666666666"/>
    </map>
</property>

5.8)使用p命名空间简化配置(了解)

  • 名称:p:propertyName,p:propertyName-ref

  • 类型:属性

  • 归属:bean标签

  • 作用:为bean注入属性值

  • 格式:

    <bean p:propertyName="propertyValue" p:propertyName-ref="beanId"/>
    
  • 注意:使用p命令空间需要先开启spring对p命令空间的的支持,在beans标签中添加对应空间支持

    <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="userService"
           class="com.itheima.service.impl.UserServiceImpl"
           p:userDao-ref="userDao"
           p:bookDao-ref="bookDao"
           />
    

5.9)SpEL (了解)

  • Spring提供了对EL表达式的支持,统一属性注入格式

  • 类型:属性值

  • 归属:value属性值

  • 作用:为bean注入属性值

  • 格式:

    <property value="EL"></bean>
    
  • 注意:所有属性值不区分是否引用类型,统一使用value赋值

  • 所有格式统一使用 value=“********”

    • 常量 #{10} #{3.14} #{2e5} #{‘itcast’}

    • 引用bean #{beanId}

    • 引用bean属性 #{beanId.propertyName}

    • 引用bean方法 beanId.methodName().method2()

    • 引用静态方法 T(java.lang.Math).PI

    • 运算符支持 #{3 lt 4 == 4 ge 3}

    • 正则表达式支持 #{user.name matches‘[a-z]{6,}’}

    • 集合支持 #{likes[3]}

  • 案例:

     <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
         <property name="userDao" value="#{userDao}"/>
         <property name="bookDao" value="#{bookDao}"/>
         <property name="num" value="#{666666666}"/>
         <property name="version" value="#{'itcast'}"/>
    </bean>
    

5.10)properties文件

  • Spring提供了读取外部properties文件的机制,使用读取到的数据为bean的属性赋值

  • 操作步骤

    1.准备外部properties文件

    2.开启context命名空间支持

    xmlns:context="http://www.springframework.org/schema/context"
    

​ 3.加载指定的properties文件

<context:property-placeholder location="classpath:filename.properties">

​ 4.使用加载的数据

<property name="propertyName" value="${propertiesName}"/>
  • 注意:如果需要加载所有的properties文件,可以使用*.properties表示加载所有的properties文件

  • 注意:读取数据使用**${propertiesName}格式进行,其中propertiesName**指properties文件中的属性名

5.11)团队开发

  • 名称:import

  • 类型:标签

  • 归属:beans标签

  • 作用:在当前配置文件中导入其他配置文件中的项

  • 格式:

    <beans>
        <import />
    </beans>
    
  • 基本属性:

    <import resource=“config.xml"/>
    

​ resource:加载的配置文件名

  • Spring容器加载多个配置文件

    new ClassPathXmlApplicationContext("config1.xml","config2.xml");
    
  • Spring容器中的bean定义冲突问题

    • 同id的bean,后定义的覆盖先定义的

    • 导入配置文件可以理解为将导入的配置文件复制粘贴到对应位置

    • 导入配置文件的顺序与位置不同可能会导致最终程序运行结果不同

5.12)ApplicationContext

1.ApplicationContext是一个接口,提供了访问spring容器的API

2.ClassPathXmlApplicationContext是一个类,实现了上述功能

3.ApplicationContext的顶层接口是BeanFactory

4.BeanFactory定义了bean相关的最基本操作

5.ApplicationContext在BeanFactory基础上追加了若干新功能

对比BeanFactory

1.BeanFactory创建的bean采用延迟加载形式,使用才创建

2.ApplicationContext创建的bean默认采用立即加载形式

FileSystemXmlApplicationContext

可以加载文件系统中任意位置的配置文件,而ClassPathXmlApplicationContext只能加载类路径下的配置文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值