A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zeroHe 中级黑马   /  2019-1-29 16:01  /  1031 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

【spring-04】

01 JdbcTemplate

    00 spring 模版类
        JdbcTemplate、HibernateTemplate、RedisTemplate、JmsTemplate

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>  

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

<?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">

    <bean id="accountDao" class="com.spring.dao.impl.AccountDaoJdbcTemplateImpl">
        <property name="template" ref="jdbcTemplate"></property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="springDataSource"></property>
    </bean>

【spring内置数据源】
    <bean id="springDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdemo"/>
        <property name="username" value="root"/>
        <property name="password" value="root123"/>
    </bean>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:jdbcConfig.properties"/>
    </bean>

    <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdemo
jdbc.username=root
jdbc.password=root123


    01 基于JdbcTemplate的CRUD

        template.update("insert into acc、ount (name,money) values ('ddd',12.12)");

        template.update("update account set money = 20 where id = 4");

        template.update("delete from account where id = 4");

        List<Account> accountList = template.query("select * from account where id != ?", new BeanPropertyRowMapper<Account>(Account.class), 4);

        Account account = template.queryForObject("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);

        Long count = template.queryForObject("select count(*) from account where id <> ?", Long.class, 0);

02 spring事务

    01 spring事务管理器接口 PlatformTransactionManager

    02 真正管理事务的对象
        org.springframework.jdbc.datasource.DataSourceTransactionManager  
        用 使用 SpringJDBC 或 或 iBatis  进行持久化数据时使用

        org.springframework.orm.hibernate5.HibernateTransactionManager
        使用Hibernate

    03 事务隔离级别
        数据库默认隔离级别(以下其中一种)
        读未提交、读已提交(oracle)、可重复性读(mysql)、序列化

    04 事务的传播行为

REQUIRED:
    如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)

SUPPORTS:
    支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)

MANDATORY:
    使用当前的事务,如果当前没有事务,就抛出异常

REQUERS_NEW:
    新建事务,如果当前在事务中,把当前事务挂起。

NOT_SUPPORTED:
    以非事务方式执行操作,如果当前存在事务,就把当前事务挂起

NEVER:
    以非事务方式运行,如果当前存在事务,抛出异常

NESTED:
    如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作。

    05 超时时间
        默认值是-1,没有超时限制。如果有,以秒为单位进行设置

03 基于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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.spring.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <bean id="accountDao" class="com.spring.dao.impl.AccountDaoJdbcTemplateImpl">
        <property name="dataSource" ref="springDataSource"/>
    </bean>

    <bean id="springDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdemo"/>
        <property name="username" value="root"/>
        <property name="password" value="root123"/>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="springDataSource"/>
    </bean>

    <!--配置事物的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 指定方法名称:是业务核心方法
            read-only:是否是只读事务。默认 false,不只读。
            isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
            propagation:指定事务的传播行为。
            timeout:指定超时时间。默认值为:-1。永不超时。
            rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
            没有默认值,任何异常都回滚。
            no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回
            滚。没有默认值,任何异常都回滚。
            -->
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!--配置aop-->
    <aop:config>
        <!--切入点表达式-->
        <aop:pointcut id="pc_1" expression="execution(* com.spring.service.impl.*.*(..))"/>
        <!--建立切入点表达式与事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc_1"/>
    </aop:config>
</beans>

04 基于注解的事务控制

【spring-03】

01 AOP  Aspect Oriented Programming 面向切面编程

    00 基础
        动态代理

    01 作用
        在程序运行期间,不修改源码对已有方法进行增强

    02 优势
        减少重复代码、提高开发效率、维护方便


02 动态代理 基于接口 JDK 代理

    01 接口、接口的实现类(被代理对象)、如何代理(InvocationHandler)

final Actor actor = new Actor();//直接

IActor proxyActor = (IActor) Proxy.newProxyInstance(
    actor.getClass().getClassLoader(),
    actor.getClass().getInterfaces(),
    new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {

        Object rtValue = null;
        rtValue = method.invoke(actor, args);
        return rtValue;

        }
});

03 动态代理 基于子类 cglib代理

    01 类(不能是final)

        <dependency>
            <groupId>org.sonatype.sisu.inject</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.1-v20090111</version>
        </dependency>

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ProducerImpl.class);
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                String methodName = method.getName();
                System.out.println(methodName);
                Object ret = methodProxy.invokeSuper(o,objects);
                return ret;
            }
        });
        ProducerImpl producer = (ProducerImpl) enhancer.create();

04 Spring AOP

   01 概念
        Joinpoint( 连接点)
        Pointcut( 切入点)
        Advice( 通知/ 增强)
        Introduction( 引介)
        Target( 目标对象)
        Weaving( 织入)
        Proxy (代理)
        Aspect( 切面)

    02 基于 xml 的 AOP

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>

<?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 id="logger" class="com.spring.aop.Logger"></bean>

        <aop:config>
        <aop:pointcut id="pc_1" expression="execution(* com.spring.aop.*.*(..))"/>

        <!--order 数字小,优先级高-->
        <aop:aspect id="logAdvice" ref="logger" order="2">
            <aop:before method="beforePrintLog" pointcut-ref="pc_1"/>
            <aop:after-returning method="afterReturnPrintLog" returning="retValue" pointcut-ref="pc_1"/>
            <aop:after-throwing method="afterThrowingPrintLog" throwing="throwable" pointcut-ref="pc_1"/>
            <aop:after method="afterPrintLog" pointcut-ref="pc_1"/>
            <!--ProceedingJoinPoint is only supported for around advice-->
            <!--<aop:around method="aroundPrintLog" pointcut-ref="pc_1"/>-->
        </aop:aspect>

        </aop:config>
</beans>

    public Object aroundPrintLog(ProceedingJoinPoint joinPoint){
        Object retValue = null;
        try {
            Object[] args = joinPoint.getArgs();
            System.out.println("前置通知:---参数为:");
            System.out.println(Arrays.toString(args));
            retValue = joinPoint.proceed(args);
            System.out.println("后置通知:---");
            return retValue;
        } catch (Throwable throwable) {
            System.out.println("异常通知:---");
            throw new RuntimeException(throwable);
        }finally {
            System.out.println("最终通知:---");
        }
    }

    03 基于注解的AOP

        <!-- 开启 spring 对注解 AOP 的支持 -->
        <aop:aspectj-autoproxy/>

        @Aspect// 表示当前类是一个切面类

        @Pointcut("execution(* com.spring.aop.*.*(..))")
        private void pt1(){}

        @Before("pt1()")
        public void beforePrintLog(){}

        @AfterReturning(value = "pt1()",returning = "retValue")
        public void afterReturnPrintLog(Object retValue){}

        @AfterThrowing(value = "pt1()",throwing = "throwable")
        public void afterThrowingPrintLog(Throwable throwable){}

        @After("pt1()")
        public void afterPrintLog(){}

        @Around(value = "pt1()",argNames = "joinPoint")
        public Object aroundPrintLog(ProceedingJoinPoint joinPoint){}

【spring-02】

01 基于 IOC 的 CRUD
    01 void save(T t)
    02 void update(T t)
    03 void deleteById(Integer id)
    04 T findById(Integer id)
    05 List<T> findAll()

    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <constructor-arg name="ds" ref="comboPooledDataSource"></constructor-arg>
    </bean>

    <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

02 基于注解

<?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.spring"></context:component-scan>

</bean>


    @Component @Controller @Service @Repository

    @Autowired @Qualifier

01 @Autowired

自动按照类型注入。
当使用注解注入属性时,set方法可以省略。
它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id
在 spring 容器查找,找到了也可以注入成功。找不到就报错。

02 @Qualifier

在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和
@Autowire 一起使用;但是给方法参数注入时,可以独立使用。


    @Resource

    @Value
        注入基本数据类型和 String 类型数据的

    @Scope @PostConstruct/*指定初始化方法*/ @PreDestroy/*指定销毁方法*/


03 纯注解【了解】

    @Configuration @ComponentScan
    @Bean(name = "dataSource") @Value("${jdbc.driver}")
    @Import

    ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class);

04 spring整合junit【掌握】

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

/**
* spring 5.0 版本需要对应 junit 4.12 版本
*/
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(classes = SpringConfig.class)
@ContextConfiguration(locations = "classpath:applicationContextAnnotation.xml")
UserServiceTest



【spring-01】
00 文档:spring-framework-5.0.2.RELEASE-docs/spring-framework-reference/index.html

01 spring

        IOC 控制反转                Inverse Of Control
        AOP 面向切面编程        Aspect Oriented  Programming

02 spring 优势

        01 方便解耦,简化开发
        02 AOP 编程的支持
        03 声明式事务的支持
        04 方便程序测试
        05 方便继承各种优秀框架
        06 降低 JavaEE API 的使用难度
       
03 spring 体系结构

04 IOC

    01 下载 spring【version:5.0.2】
        01 link:http://repo.springsource.org/libs-release-local/org/springframework/spring
        02 【注意】spring5  版本是用 jdk8  编写的
            所以要求我们的 jdk 版本是 8  及以上。
            同时 tomcat  的版本要求 8.5  及以上

    02 AccountService AccountServiceImpl
    03 AccountDao AccountDaoImpl

05 基于 xml

    00 spring 依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

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

    <bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"></bean>

    <bean id="userService" class="com.spring.service.impl.UserServiceImpl"
          scope="singleton"
          init-method="init" destroy-method="destroy">

        <property name="userDao" ref="userDao"></property>
    </bean>

<beans>

06 ApplicationContext
    01 常用的三个子类
         *      01 ClassPathXmlApplicationContext
         *      02 FileSystemXmlApplicationContext
         *      03 AnnotationConfigApplicationContext


07 IOC bean标签

id:给对象在容器中提供一个唯一标识。用于获取对象。
class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。

scope:指定对象的作用范围。
* singleton :默认值,单例的.
* prototype :多例的.
* request  :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
* session  :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
* global session  :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么
globalSession 相当于 session.

init-method:指定类中的初始化方法名称。
destroy-method:指定类中销毁方法名称。

08 实例化bean的三种方式

    01 使用默认的无参数构造函数
        <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"/>

    02 使用静态工厂的方法创建对象

public class StaticFactory {
    public static IAccountService createAccountService(){
        return new AccountServiceImpl();
    }
}

    <bean id="accountService"
    class="com.itheima.factory.StaticFactory"
    factory-method="createAccountService"></bean>

    03 使用实例工厂的方法创建对象

public class InstanceFactory {
    public IAccountService createAccountService(){
        return new AccountServiceImpl();
    }
}

    <bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean>

    <bean id="accountService"
    factory-bean="instancFactory"
    factory-method="createAccountService"></bean>

09 DI 依赖注入(给属性赋值)

    01 构造函数注入

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
    <constructor-arg name="name" value=" 张三 "></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="birthday" ref="myBirthday"></constructor-arg>
    【指定格式的日期】
</bean>

<bean id="myBirthday" factory-bean="simpleDateFormat" factory-method="parse">
    <constructor-arg value="1994-12-22"></constructor-arg>
</bean>

<bean id="simpleDateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg name="pattern" value="yyyy-MM-dd"></constructor-arg>
</bean>

    02 set 方法注入

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
    <property name="name" value="test"></property>
    <property name="age" value="21"></property>
</bean>

    03 集合属性输入
        String[] myStrs
        List<String> myList
        Set<String> mySet
        Map<String,String> myMap
        Properties myProps

        List结构:array、list、set[value]
        Map结构:map、entry、props、prop

        注入空值:<null></null>


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马