Spring框架使用

Spring基本案例

导入Spring相关jar包
<bean id="user" class="Spring5.User"></bean>  xml文件

//调用spring配置文件
ApplicationContext context=new FileSystemXmlApplicationContext("beal.xml");
//获取配置创建的对象
User user = context.getBean("user", User.class);

//通过对象调用方法
user.add();

Ioc(控制反转):把创建对象和对象之间的调用交给spring管理

Ioc思想局域IOC容器完成,IOC容器底层就是对象工厂

Ioc底层原理:xml解析、反射、工厂模式

Ioc接口:BeanFactory(加载配置文件时不创建对象,在获取(使用)对象才创建)Spring内置接口,不提供开发使用
ApplicationContext(加载配置文件时创建对象):BeanFactory子接口,功能更强,开发人员使用
              new ClassPathXmlApplicationContext(类路径)
new FileSystemXmlApplicationContext(硬盘路径)
IOC操作bean管理(基于Xml方式)
1.创建对象
  1. Xml中使用bean标签,标签中添加对应属性,就可以实现对象创建
  2. Id:唯一标识  class:类全路径(包类路径)
  3. 默认使用无参构造方法
2.注入属性
 2-1.DI:依赖注入,就是注入属性
  1. 通过set方法注入
11、通过bean标签里面的<property name="属性名称" value="向属性注入的值"></property>
属性中设置空值<property name="属性名称"> <null></null>
</property>
属性中设置特殊符号值<property name="属性名称"> <value><![CDATA[特殊值]]></value>
</property>
12、通过p名称空间注入:<beans中添加xmlns:p="http://www.springframework.org/schema/p">
<bean id="唯一标识" class="类全路径" p:属性值=“”></bean>

   2、通过有参方法注入

          通过bean标签里面的<constructor-arg index=”有参构造中的顺序name="属性名称" value="向属性注入的值"></constructor-arg>
2-2外部Bean  通过set方法注入
<bean id="userserive" class="Spring5.Userservice">

    <property name="user" ref="userimpl"></property>

</bean>

<bean id="userimpl" class="sevice.Userimpl"></bean>
2-3内部bean(对象类型)
1)一对多
     <bean id="userserive" class="Spring5.Userservice">

    <property name=" "></property>

   属性内部嵌套 <property name="user1">

        <bean id="user1" class="">
<property name=" " ref="">
</bean>

              </property>

               </bean>
 2-4 级联赋值
<bean id="userserive" class="Spring5.Userservice">

    <property name="user" ref="userimpl"></property>

第一种  通过外部bean引入<property name="" ref="userimpl"></property>
第二种  通过<property name="对象.属性"value="赋值"></property>(需要生成对象属性的get方法)

</bean>

<bean id="userimpl" class="sevice.Userimpl">

    <property name="" value=""></property>

</bean>
2-3数组及集合注入
  1. 创建类,定义数组、Listmapset类型属性,生成对应set方法
  2. Spring配置文件配置

<bean id="名称(随便起)" class="类所在位置">
    <
property name="list类型">
        <
list>
            <
value>要输入的值</value>
        </
list>
    </
property>
    <
property name="普通数组">
        <
array>
               <
value>要输入的值</value>
        </
array>
    </
property>
    <
property name="set类型">
        <
set>
             <
value>要输入的值</value>
        </
set>
    </
property>
    <
property name="map类型">
        <
map>
            <
entry key="key" value="value"></entry>
                    </
map>
    </
property>
</
bean>

2-3-1 集合中设置对象类型值
        <property name="list对象名">

    <list>

        <ref bean="外部bean名称"></ref>

    </list>

</property>
 

<bean id="ref中对应" class="对应类的位置">
    <
property name="对象属性" value="输入值"></property>
</
bean>

2-3-2提取集合外部注入使用
1)添加名称空间utilxmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation中添加http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
2<util:list id="与下面对应">

    <value>输入的值 </value>

      <ref></ref>

   </util:list>

<bean id="随便写" class="对应类的位置">

    <property name="对应类的属性名称" ref="应用外部的util"></property>

</bean>

Spring的两种bean

一种为普通bean(在配置文件中定义bean类型就是返回类型)

一种为工厂bean(FactoryBean)在配置文件中定义的bean类型可以和返回类型不一样

  1. 创建类,实现FactoryBean接口,作为工厂bean
  2. 实现接口中的方法,在实现中的方法中定义返回的bean类型
  3. FactoryBean接口中的getObject()方法返回类型为修改后的类型
bean作用域  
bean中的scope属性值(prototype多实例,不在加载spring配置文件时创建对象,在调用getBean方法是才创建多实例对象和singleton单实例,加载spring配置文件时候就会创建单实例对象,requestsession),默认单实例
bean生命周期
  1. 创建bean实例(无参构造)
  2. bean的属性设置值或者调用方法
  3. 调用bean的初始化方法(bean配置文件的属性init-method
  4. 使用bean
  5. 容器关闭,调用bean的销毁方法(bean配置文件的属性destroy-method
       后置处理器,可以在(3bean的初始化方法前后
           1)创建类,实现接口BeanPostProcessor ,创建后置处理器,重写接口中的方法

 Xml自动装配(制定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入)

   Bean标签属性autowire(byName根据属性名称注入,注入Bean的id值和类属性名称一样,byType根据属性类型注入)

 外部属性文件(数据库连接池(德鲁伊连接池))

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <
property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <
property name="url" value="jdbc:mysql://localhost:3306/test"></property>
    <
property name="username" value="root"></property>
    <
property name="password" value="root"></property>
</
bean>

 引用外部属性文件配置

  1. 创建文件后缀为properties的文件
            prop.driverClassName=com.mysql.jdbc.Driver

prop.url=jdbc:mysql://localhost:3306/test

prop.username=root

prop.password=123456
    2)通过名称空间context

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

xsi:schemaLocation=添加http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

//引入外部属性文件

<context:property-placeholder location="classpath:文件后缀为properties"/>

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClassName}"></property>
        <
property name="url" value="${prop.url}"></property>
        <
property name="username" value="${prop.username}"></property>
        <
property name="password" value="${prop.password}"></property>
    </
bean>

IOC操作bean管理(基于注解方式)

       对象注解

1、@Component是所有受Spring 管理组件的通用形式
2、@Service(对应业务层Bean
3、@Controller(对应控制器的Bean
4、@Repository(对应数据访问层Bean
引入context名称空间
//组件扫描

<context:component-scan base-package="添加要扫描的类的文件路径"></context:component-scan>

  类名上添加@Componentvalue属性值可以省略不写,默认类名称,首字母小写)

<context:component-scan base-package="" use-default-filters="false">
    <
context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</
context:component-scan>

use-default-filters="false"表示自己配置filter,不使用默认filters
context:include-filter设置扫描哪些内容
不加use-default-filters,默认扫描所有,context:exclude-filter设置哪些内容不进行扫描

<context:component-scan base-package="">
    <
context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</
context:component-scan>

注解方式进行属性注入
属性注解
  1. @Autowired(根据属性类型进行自动装配)servicedao类上添加对象注解在属性上添加注解,不需要添加set方法
  2. @Qualifier(根据属性名称进行注入)和(1)一起使用
  3. @Resource(可以根据类型注入,也可以根据名称注入)
  4. @Value(value=”要注入的值”)(普通类型属性注入)
全注解开发

@Configuration//作为配置类,替代xml文件

@ComponentScanbasePackages=(“类路径”))

配置类上添加以上两个

@EnableAspectJAutoProxy(proxyTargetClass = true)//开启Aspect生成代理对象

测试方法中new AnnotationConfigApplicationContext(配置类的class)

AOP(面向切面编程)

底层原理:jdk动态代理(有接口,实现),CGLB动态代理(没接口,继承)

术语:连接点(类中那些方法可以被增强),
切入点(实际被增强的逻辑部分),
通知(实际增强的方法)的配置
AspectJ注解
spring配置文件中,开启注解扫描
使用注解创建增强类和被增强类
在增强类上面添加注解@Aspect
spring配置文件中生成代理对象
引入名称空间contextaop

<!--开启aspectJ生成对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

相同切入点抽取

@Pointcut下面写方法将方法名填入到通知的value

  1. 前置通知(@Before
  2. 后置通知(@After
  3. 环绕通知(@Around
  4. 异常通知(@AfterThrowing
  5. 最终通知(@AfterReturning
增强的方法上面写
切面(把通知运用到切入点的过程)
 Spring框架基于AspectJ实现AOP框架
切入点表达式(知道对哪个类的哪个方法进行增强)
execution[权限修饰符*(表示任意修饰符)][返回类型(可以省略不写)][类全路径][方法名称][参数列表]
多个增强类可以设置@Ordex(数字越小优先级越高)

事务(添加至service层):应用程序中一系列严密的操作,所有操作必须成功完成,否则在每个操作中所作的所有更改都会被撤消。

事务的四大特性分别是:原子性、一致性、隔离性、持久性

两种事务管理方式:编程式和声明式事务管理

Spring声明式事务管理,底层使用AOP原理

  1. 开启事务
  2. 进行业务操作
  3. 没有异常,提交事务
  4. 出现异常,事务回滚
Spring事务管理器API(PlatformTransactionManager

Spring配置文件中配置事务管理器

<!—创建事务管理器-->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<!--注入数据源-->
    <
property name="dataSource" ref="dataSource(对应数据库的)"></property>
</
bean>

引入名称空间tx

<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

@Transactional(类(所有方法都添加事务)和方法上面都可以)

@Transactional属性propagation:事务传播行为(7种)

1、PROPAGATION_REQUIRED

2、PROPAGATION_SUPPORTS:

3、PROPAGATION_MANDATORY

4、PROPAGATION_REQUIRES_NEW

5、PROPAGATION_NOT_SUPPORTED

6、PROPAGATION_NEVER

7、PROPAGATION_NESTED

8、PROPAGATION_NESTED

                  ioSlation:事务隔离级别(4种)             

                  1.Read uncommitted(读未提交)

                  2.Read committed(读已提交)

                  3.Repeatable read(可重复读)

                  4.Serializable(可序化or串行化)

                  timeout:超时时间,默认值-1,以秒为单位计算

                  readOnly:是否只读,默认值false,表示可以查询,若为true,只能查询

                  rollbackFor:回滚,设置那些异常进行回滚

                  noRollbackFor:不回滚,设置出现异常不进行回滚

事务操作(完全直接开发)  

@Configuration//配置类

@ComponentScan()//组件扫描

@EnableTransactionManagement//开启事务

//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource(){
   
DruidDataSource druidDataSource = new DruidDataSource();
   
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
   
druidDataSource.setUrl("jdbc:mysql://localhost:3306/数据库名");
   
druidDataSource.setUsername("账号");
   
druidDataSource.setPassword("密码");
   
return druidDataSource;
}

//创建JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DruidDataSource druidDataSource){
   
JdbcTemplate jdbcTemplate=new JdbcTemplate();
   
jdbcTemplate.setDataSource(druidDataSource);
 
return jdbcTemplate;
}

//创建事务管理器
@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DruidDataSource druidDataSource){
DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(druidDataSource);
return  dataSourceTransactionManager;
}

标记@Nullable属性可以为空

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值