Spring笔记

视频地址

IOC

UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoMySqlImpl() );
service.getUser();
//那我们现在又想用Oracle去实现呢
service.setUserDao( new UserDaoOracleImpl() );
service.getUser();

以前所有东西都是由程序去进行控制创建 , 而现在是由我们自行控制创建对象 , 把主动权交给了调用者 . 程序不用去管怎么创建,怎么实现了 . 它只负责提供一个接口 .

这种思想 , 从本质上解决了问题 , 我们程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

上一层和下一层设置了一个接口

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

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

在这里插入图片描述

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

快速上手Spring

public class Hello {
    private String name;

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

    public void show(){
        System.out.println("Hello,"+ name	 );
    }
}
<?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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

  <!--  Id		  变量名   				   class 	new 的对象
		Property  给对象中的属性设置一个值   	 value 	  值的内容		-->
    <bean id="hello" class="zhang.pojo.Hello">
        <property name="name" value="hello spring" />
    </bean>

</beans>
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Hello hello = (Hello) context.getBean("hello");
    
    //没有别名的方式
    Hello hello = (Hello) context.getBean(Hello.class);
    
    hello.show();
}

Spring配置

别名可以定义多个,但是id属性只能有⼀个值

  • XML的id属性的值,命名要求:必须以字⺟开头,字⺟ 数字 下划线 连字符不能以特殊字符开头 /person
  • name属性的值, 命名没有要求 /person
<!--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="zhang.pojo.Hello">
   <property name="name" value="Spring"/>
</bean>

团队的合作通过import来实现 .

<import resource="{path}/beans.xml"/>

注入

通过Spring⼯⼚及配置⽂件,为所创建对象的成员变量赋值

为什么需要注⼊?

通过编码的⽅式,为成员变量进⾏赋值,存在耦合

好处:解耦合

<bean id="person" name="p" class="com.baizhiedu.basic.Person">
	<property name="id">
		<value>20</value>
	</property>
	<property name="name">
		<value>zy</value>
	</property>
</bean>

<!--	value 属性只能简化8种基本类型 + String 注入标签-->
<bean id="person" name="p" class="com.baizhiedu.basic.Person">
    <property name="id" value="20"/>
    <property name="name" value="zy"/>
</bean>

<!--基于p命名空间的简化-->
<bean id="person" name="p" class="com.baizhiedu.basic.Person" p:id="20" p:name="zy"/>

P:中间按alt+enter 选择Create namespace declaration

xmlns:p="http://www.springframework.org/schema/p"
<!-- 数组 -->
<property name="addresses">
  <list>
      <value>zpark</value>
      <value>shangdi</value>
      <value>xierq</value>
      <value>xierq</value>
      <value>xierq</value>
  </list>
</property>
<!-- Set集合 -->
<property name="tels">
    <set>
        <value>138111111</value>
        <value>139111111</value>
        <value>166111111</value>
        <value>166111111</value>
        <value>166111111</value>
    </set>
</property>
<!-- List集合 -->
<property name="addresses">
  <list>
      <value>zpark</value>
      <value>shangdi</value>
      <value>xierq</value>
      <value>xierq</value>
      <value>xierq</value>
  </list>
</property>

<!-- Map集合 -->
<!--注意: map -- entry -- key有特定的   标签 <key></key>
 						  值根据对应类型选择对应类型的标签-->
<property name="qqs">
  <map>
     <entry>
         <key><value>suns</value></key>
         <value>3434334343</value>
     </entry>
     <entry>
         <key><value>chenyn</value></key>
         <value>73737373</value>
     </entry>
  </map>
</property>

<!--Properties类型 特殊的Map key=String
						   value=String-->
<props>
     <prop key="key1">
         value1
    </prop>
    
     <prop key="key2">
         value2
    </prop>
</props>
Map<String, String> qqs = person.getQqs();
Set<String> keys = qqs.keySet();    //通过keySet获得对象里的key    然后通过对象.get(key)获得value
for (String key : keys) {
    System.out.println(key + " value is " + qqs.get(key));
}

自定义类型赋值

<!--第一种方式-->
<bean id="userService" class="com.baizhiedu.basic.UserServiceImpl">
    <property name="userDAO">
        <bean class="com.zhang.basic.UserDAOImpl"/>
    </property>
</bean>

<!--第二种方式-->
<bean id="userDAO" class="com.baizhiedu.dao.UserDAOImpl"></bean>
<bean id="userService" class="com.baizhiedu.service.UserServiceImpl">
    <property name="userDAO">		 
        <ref bean="userDAO"/>
    </property>
</bean>
<!--基于属性简化-->
<property name="userDAO" ref="userDAO"/>

<!--基于p命名空间的简化-->
<bean id="userDAO" class="com.baizhiedu.dao.UserDAOImpl"></bean>

<bean id="userService" class="com.baizhiedu.service.UserServiceImpl" p:userDAO-ref="userDAO"/>

构造注入

无参

<bean id="user" class="zhang.pojo.User">
    <property name="name" value="tt"/>
</bean>

<!--取别名-->
<alias name="user" alias="dsadfasdfsd"/>
public void Usertest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) context.getBean("user");
    user.show();
}

有参

<!-- 第一种根据index参数下标设置 -->
<constructor-arg index="0" value="t2"/>
<!-- 第二种根据参数名字设置 -->
<constructor-arg name="name" value="t2"/>
<!-- 第三种根据参数类型设置 -->
<constructor-arg type="java.lang.String" value="t2"/>

c 命名空间注入

xmlns:c="http://www.springframework.org/schema/c"
<bean id="user222" class="zhang.pojo.User" c:name="ttt" />

Bean的作用域

 <bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
     
     
 <bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  
  或者
 <bean id="account" class="com.foo.DefaultAccount" singleton="false"/>

自动装配

自动装配说明

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;
  2. 在java中显式配置;
  3. 隐式的bean发现机制和自动装配。

这里我们主要讲第三种:自动化的装配bean。

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少。

推荐不使用自动装配xml配置 , 而使用注解 .

autowire byName (按名称自动装配)

<bean id="dog" class="zhang.pojo.Dog"/>
<bean id="cat" class="zhang.pojo.Cat"/>
<!--原来-->
<bean id="user" class="zhang.pojo.User">
    <property name="cat" ref="cat"/>
    <property name="dog" ref="dog"/>
    <property name="str" value="tt"/>
</bean>

<!--现在-->
<bean id="user" class="zhang.pojo.User" autowire="byName">
    <property name="str" value="tt"/>
</bean>

autowire byType (按类型自动装配)

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

使用注解

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

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<context:annotation-config/>
@Autowired
@Qualifier
  • @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
  • @Qualifier不能单独使用。
<bean id="dog" class="zhang.pojo.Dog"/>
<bean id="dog2" class="zhang.pojo.Dog"/>
@Autowired
@Qualifier(value = "dog")
private Dog dog;
@Resource
  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 不成功,则按byType的方式自动装配。
  • 或者
@Resource(name = "dog2")
<bean id="dog3" class="zhang.pojo.Dog"/>
<bean id="dog2" class="zhang.pojo.Dog"/>
  • 都不成功,则报异常。

注解开发

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

    <!--指定注解扫描包-->
    <context:component-scan base-package="com.zhang"/>
    <!--开启属性注解支持-->
    <context:annotation-config/>
    
    
</beans>

在指定包下编写类,增加注解

//等价于<bean id="user" class="com.zhang.pojo.User"/>
@Component
public class User {
    public String name = "zy" ;
}

可以不用提供set方法,直接在直接名上添加@value(“值”)

//等价于<property name="name" value="zy"/>
@Value("zy")
public String name  ;

@Component三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

  • @Controller:web层
  • @Service:service层
  • @Repository:dao层

@Scope(“prototype”)

  • XML可以适用任何场景 ,结构清晰,维护方便
  • 注解不是自己提供的类使用不了,开发简单方便

基于Java类进行配置

//这个类被Spring接管,注册到了容器中
@Component
//@ComponentScan("zhang.pojo")
//@Import(MyConfig2.class)  //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class User {
    @Value("asd")	//属性注入值
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
//这个也会被Spring容器托管,注册到容器中	本身就是一个@Component
//Configuration代表这是一个配置类,applicationContext.xml
@Configuration
public class ZhangConfig {
    @Bean	 //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
    public User getUser(){
        return new User();
    }
}
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ZhangConfig.class);
User user = (User) context.getBean("getUser");
String name = user.getName();
System.out.println("name = " + name);

动态代理

public class ProxyInvocationHandler implements InvocationHandler {
    private Rent rent;
    public void setRent(Rent rent) {
        this.rent = rent;
    }
    //生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色
    //this 代表InvocationHandler	调用它来处理
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);

    }
    // proxy : 代理类 method : 代理类的调用处理程序的方法对象.
    // 处理代理实例上的方法调用并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        //核心:本质利用反射实现!
        Object result = method.invoke(rent, args);
        fare();
        return result;
    }
    //看房
    public void seeHouse(){
        System.out.println("带房客看房");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}
public class Client {
    public static void main(String[] args) {
        //房东要租房
        Host host = new Host();
        Host host2 = new Host();
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setRent(host);	//这里可以有很多房东 如host、host2
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
    }
}

AOP

使用AOP织入,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

通过 Spring API 实现

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void search();
}
public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加用户");
    }
    public void delete() {
        System.out.println("删除用户");
    }
    public void update() {
        System.out.println("更新用户");
    }
    public void search() {
        System.out.println("查询用户");
    }
}
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
    }
    //method : 要执行的目标对象的方法
    //objects : 被调用的方法的参数
    //Object : 目标对象
}
public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了" + o1.getClass().getName()
                +"的"+method.getName()+"方法,"
                +"返回值:"+o);
    }
    //returnValue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
}
<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--注册bean-->
    <bean id="userService" class="zhang.service.UserServiceImpl"/>
    <bean id="log" class="zhang.log.Log"/>
    <bean id="afterLog" class="zhang.log.AfterLog"/>
    <!--aop的配置-->
    <aop:config>
        <!--切入点 expression:表达式匹配要执行的方法-->
        <aop:pointcut id="pointcut" expression="execution(* zhang.service.UserServiceImpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.search();
}

自定义类来实现Aop

public class DiyPointcut {
    public void before(){
        System.out.println("---------方法执行前---------");
    }
    public void after(){
        System.out.println("---------方法执行后---------");
    }
}
<!--注册bean-->
<bean id="userService" class="zhang.service.UserServiceImpl"/>
<bean id="diy" class="zhang.diy.DiyPointcut"/>

<!--aop的配置-->
<aop:config>
<!--第二种方式:使用AOP的标签实现-->
    <aop:aspect ref="diy">
        <aop:pointcut id="diyPonitcut" expression="execution(* zhang.service.UserServiceImpl.*(..))"/>
        <aop:before pointcut-ref="diyPonitcut" method="before"/>
        <aop:after pointcut-ref="diyPonitcut" method="after"/>
    </aop:aspect>
</aop:config>
@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.search();
}

使用注解实现

package zhang.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnotationPointcut {
    @Before("execution(* zhang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("---------方法执行前---------");
    }

    @After("execution(* zhang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("---------方法执行后---------");
    }

    @Around("execution(* zhang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法proceed
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}
<bean id="userService" class="zhang.service.UserServiceImpl"/>
<bean id="annotationPointcut" class="zhang.diy.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>
@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.search();
}

回忆MyBatis

编写pojo实体类

public class User {
    private int id;  //id
    private String name;   //姓名
    private String pwd;   //密码
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

实现mybatis的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.zhang.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.zhang.mapper"/>
    </mappers>
</configuration>

UserDao接口编写

public interface UserMapper {
   public List<User> selectUser();
}

接口对应的Mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.mapper.UserMapper">
    <select id="selectUser" resultType="user">
    select * from user
   </select>
</mapper>

测试类

@Test
public void selectUser() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.selectUser();
    for (User user: userList){
        System.out.println(user);
    }
    sqlSession.close();
}

整合实现

<dependencies>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

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

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>


</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

方式一

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

    <!--配置数据源替换mybaits的数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

    <!--配置SqlSessionFactory,关联MyBatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--关联Mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zhang/mapper/*.xml"/>
    </bean>

    <!--注册sqlSessionTemplate , 关联sqlSessionFactory  就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--利用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <import resource="spring-dao.xml"/>
    <!--注册bean实现-->
    <bean id="userMapper" class="com.zhang.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>
//增加Dao接口的实现类;私有化sqlSessionTemplate
public class UserMapperImpl implements UserMapper {
    //sqlSession不用我们自己创建了,Spring来管理
    private SqlSessionTemplate sqlSession;
    public void setSqlSession(SqlSessionTemplate sqlSession) {	//set后与注册bean中的 name="sqlSession" 对应
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

测试

@Test
public void selectUser2() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
    UserMapper userDao = (UserMapper) context.getBean("userMapper");
    for (User user : userDao.selectUser()) {
        System.out.println(user);
    }
}

方式二

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
<!--可以省略这一步-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

<!--注册bean实现-->
<bean id="userMapper" class="com.zhang.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

事务

要么都成功,要么都失败 一致、隔离、持久

使用Spring管理事务,注意头文件的约束导入 : tx

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

http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
        <tx:method name="add" propagation="REQUIRED"/>
        <tx:method name="delete" propagation="REQUIRED"/>
        <tx:method name="update" propagation="REQUIRED"/>
        <tx:method name="search*" propagation="REQUIRED"/>
        <tx:method name="get" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<!--配置aop织入事务-->
<aop:config>
    <aop:pointcut id="txPointcut" expression="execution(* com.zhang.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值