Spring学习笔记-基础知识

来源:互联网 发布:南风知我意微盘 编辑:程序博客网 时间:2024/05/16 06:05
1.什么是Spring
    Spring是一个轻量级框架,它大大简化了java企业开发,提供了强大稳定的功能,而且没有带来额外的负担,Spring是一个解决方案.他让现有的技术更易于使用,促进良好的编程习惯
    Spring的核心组件为控制反转IOC也可以称为依赖注入DI.将类的创建和依赖关系在配置文件中配置.实现了低耦合,AOP 面向切面编程,事务等功能抽取出来单独管理,提高了代码的复用.增强了程序的维护性
2.控制反转
    控制反转的全称为Inversion Of Control 也被称为依赖注入DI(Dependency Injection),是面向对象编程的一种设计理念,用来降低程序代码间的耦合度
3.AOP和OOP的区别和联系
    1.OOP为Object Oritend Programming 面向对象编程   AOP为Aspect Oritend Programming 面向切面编程
    2.OOP为静态的代理实现 aop为动态的代理实现
    3.面向方面编程(AOP)方法是在面向对象编程(OOP)方法的基础上进行改进而来的一种创新的软件开发方法
    4.OOP 针对问题领域中以及业务处理过程中存在的实体及其属性和操作进行抽象和封装,面向对象的核心概念是纵向结构的,其目的是获得更加清晰高效的逻辑单元划分
        而 AOP则是针对业务处理过程中的切面进行提取,将这些操作与业务逻辑分离,使程序员在编写程序时可以专注于业务逻辑的处理,而利用 AOP将贯穿于各个模块间的横切关注点自动耦合进来
4.Spring的bean和Java beande的区别
    1.写法不同
        Spring bean里面对私有属性必须要构造set方法.而java bean中如果有需要则必须写上get和set方法
    2.用法不同
        Spring bean既可以用来存储数据
    3.生命
3.创建Spring配置文件applicationContext.xml
    <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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
        <bean id="name" class="cn.spring.biz.imp.StudentBizImp"></bean>
        <bean name="name" class=".....">
            <param name="" value=""></param>            //set注入法
            <param name="" ref=""></param>                
            <constructor-arg ref=""></constructor-arg>        //构造注入法
            <constructor-arg type="" value=""></constructor-arg>    //构造注入法
            <constructor-arg index="" value=""></constructor-arg>    //构造注入法
        </bean>                                //接口注入法
    </beans>
4.读取Spring配置文件的对象,管理对象的加载和生成
    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    StudentBiz sb=(StudentBiz)context.getBean("name");
    sb.say();
5.面向切面编程
    AOP (Aspect-Oriented Programming) 是软件编程思想非法占到一定阶段的产物,是对面向对象编程(OOP Object Oritented Programming)的有益的补充,AOP一般用于具有横切逻辑的场合,如访问控住.事务管理,性能检测
    1.前置增强
        public class beforeAdvice implements MethodBeforeAdvice{
            public void before(Method arg0, Object[] arg1, Object arg2){
                System.out.println("方法:"+arg0.getName()+",参数:"+Arrays.toString(arg1)+",争对对象:"+arg2);
            }
        }
    2.环绕增强
        public class AroundAdvice implements MethodInterceptor{
            public Object invoke(MethodInvocation invoke) throw Throwable{
                Method method=invoke.getMethod();        //增强的方法
                Object target=invoke.getThis();            //该方法所属的对象
                Object[] args=invoke.getArguments();        //方法的参数
                Object result=invoke.proceed();            //方法执行并返回执行的结果
                return result;
            }
        }
    
    3,最终增强
        
    4.异常抛出增强
        public class ThrowAdvice implements ThrowsAdvice{
            //前三个参数为可选...当选一个的时候..都要被选中
            public void afterThrowing([Method method,Object[] args,Object target],RuntimeException e){
                System.out.println("方法:"+method.getName()+",参数:"+Arrays.toString(args)+",所属对象:"+target+",抛出的异常:"+e)
            }
        }
    
    5.后置增强
        public class afterAdvice implements AfterReturningAdvice{
            public void afterReturning(Object arg0,Method arg1, Object[] arg2, Object arg3){
                System.out.println("方法:"+arg1.getName()+",参数:"+Arrays.toString(arg2)+",争对对象:"+arg3+",返回值为:"+arg0);
            }
        }
---------------------------------------------
    6.对于实现接口增强的applicationContext.xml文件的配置
        <bean id="before" class="cn.spring.advice.BeforeAdvice"></bean>
        <bean id="after" class="cn.spring.advice.AfterAdvice"></bean>
        <aop:config>
            <aop:pointcut expression="execution(public void say(String,String))" id="pointcut"></aop:pointcut>
            <aop:advisor advice-ref="before" pointcut-ref="pointcut"></aop:advisor>
            <aop:advisor advice-ref="after" pointcut-ref="pointcut"></aop:advisor>
        </aop:config>
=================================================================================注解给类型的增强===================================================================
1.关于前置增强的注解
    @Aspect
    public class Advice{
        //前置增强的注解方法
        @Before("execution(public void say())")
        public void before(JoinPoint point){
            String methodName=point.getSignature().getName();        //方法名
            Object[] args=point.getArgs();                    //参数对象
            Object targ=point.getTarget();                    //所属对象
        }
        //环绕增强的注解方法
        @Around("execution(public void say())")
        public Object invoke(ProceedingJoinPoint point) throw Throwable{
            String methodName=point.getSignature().getName();        //方法名称
            Object[] args=point.getArgs();                    //方法参数
            Object target=point.getTarget();                //所属对象
            Object result=point.procced();                    //方法返回结果
            return result;
        }
        //异常增强的注解方法
        @AfterThrowing(pointcut="execution(public void say())",throwing="e")
        public void  afterThrowing(JoinPoint point,RuntimeException e){
            String methodName=point.getSignature().getName();        //方法名称
            Object[] args=point.getArgs();                    //方法参数
            Object target=point.getTarget();                //所属对象
        }
        //后置增强的注解方法
        @AfterReturning(pointcut="execution(public void say())",returning="result")
        public void afterReturning(JoinPoint point,Object result){
            String methodName=point.getSignature().getName();        //方法名称
            Object[] args=point.getArgs();                    //方法参数
            Object target=point.getTarget();                //所属对象
            //result为返回的结果
        }
        //最终增强的注解方法
        @After("execution(public void say())")
        public void after(JoinPoint point){
            String methodName=point.getSignature().getName();        //方法名称
            Object[] args=point.getArgs();                    //方法参数
            Object target=point.getTarget();                //所属对象
        }    
    }
-------------------------
2.关于注解方式的applicationContext.xml配置
<bean id="advice" class="cn.spring.advice.Advice"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
-------------------------
3.关于Schema配置定义切面
<bean id="advice" class="cn.spring.advice.Advice"></bean>
<aop:config>
    <aop:pointcut expression="execution(public void say())" id="pointcut"></aop:pointcut>
    <aop:aspect ref="advice">
        <aop:before method="before" pointcut-ref="pointcut" [throwing="e"][returning="result"]></aop:before>
    </aop:aspect>
</aop:config>
============================================================================SSH的整合=====================================================================
1.创建WEB项目,添加三个框架所需要的具体jar包
=======================================================================SSH整合 Hibernate整合=======================================================================
2.配置数据源对象
    1.当存在hibernate.cfg.xml文件的时候
        1.在applicationContext.xml文件编写如下配置-定义SessionFactory Bean
            <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
            </bean>
    2.当不存在hibernate.cfg.xml文件的时候    相关的数据源框架:dbcp/c3p0/proxool
        1.添加相关的jar包    commons-dbcp-1.4.jar    commons-pool-1.6.jar
        2.在applicationContext.xml文件编写如下配置--定义DataSource Bean
            <!-- 创建数据源 -->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
                <!-- 数据库驱动 -->
                <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
                <!-- 数据库连接路径 -->
                <property name="url" value="jdbc:oarcle:thin:@localhost:1521:orcl"></property>
                <!-- 链接账户 -->
                <property name="username" value="scott"></property>
                <!-- 链接密码 -->
                <property name="password" value="13717013727"></property>
            </bean>
        3.在applicationContext.xml文件编写如下配置-定义SessionFactory Bean
            <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                <!-- 添加数据源引用 -->
                <proeprty name="dataSource" ref="dataSource"></property>
                <!-- 添加Hibernate配置参数 -->
                <property name="hibernateProperties">
                    <props>
                        <!-- 数据库方言 -->
                        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                        <!-- 是否显示SQL语句 -->
                        <prop key="hibernate.show_sql">true</property>
                        <!-- 是否格式化SQL语句 -->
                        <prop key="hibernate.format_sql">true</property>
                    </props>
                </property>
                <!-- 添加对象关系映射文件 -->
                <property name="mappingResources">
                    <list>
                        <value>cn/ssh/entity/Student.hbm.xml</value>
                        <value>cn/ssh/entity/User.hbm.xml</value>
                    </list>
                </property>
                <!-- 添加对象关系映射文件夹 -->
                <property name="mappingDirectoryLocations">
                    <list>
                        <value>classpath:cn/ssh/entity/</value>
                    </list>
                </property>
            </bean>
3.创建Dao
    1.关于Dao实现类的描述
        package cn.ssh.dao.imp;
        //继承Spring对Hibernate的技术支持模版HibernateDaoSupport
        public class StudentDaoImp extends HibernateDaoSupport implements StudentDao{
            public boolean login(Student student){
                List<Student> list=getHibernateTemplate().find("from Student where username=? and password=?",student.getUsername(),student.getPassword());
                if(list.size()==1){
                    return true;
                }
                return false;
            }
        }
    2.HibernateTemplate的相关方法
        1.Serializable save(Object entity);        //保存新的实例
        2.void delete(Object entity);            //删除指定的持久化实例
        3.void deleteAll(Collection entities);        //删除集合内部的所有持久化实例
        4.void update(Object entity);            //根据给定的持久化对象更新记录
        5.List find(String hql);            //根据hql查询字符串返回实例集合
        6.List find(String hql,Object ...value);    //根据hql查询语句,和查询体条件值返回集合 占位符用'?'
        7.Object get(Class entity,Serializable id);    //根据主键Id查询特定持久化类的实例
        8.void saveOrUpdate(Objec entity);        //根据持久化实例的状态选择保存或更新
        9.void setMaxResult(int maxResult);        //设置结果集返回的最大行数
    
    3.在applicationContext.xml文件编写如下配置
        1.创建Dao Bean
            <bean id="studentDao" class="cn.ssh.dao.imp.StudentDaoImp">
                <property name="sessionFactory" res="sessionFactory"></property>
            </bean>
4.创建Biz
    1.关于Biz实现类的描述
        package cn.ssh.biz.imp;
        public class StudentBizImp implements StudentBiz{
            private StudentDao sd;            //依赖的接口对象--需要创建setSd()方法
            //其余代码省略
        }
    2.在applicationContext.xml文件编写如下配置
        1.创建Biz Bean
            <bean id="studentBiz" class="cn.ssh.biz.imp.StudentBizImp">
                <property name="sd" ref="studentDao"></property>
            </bean>
=======================================================================SSH整合 Struts2配置=======================================================================
5.为业务层添加声明事务管理
    1.导入命名空间
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    2.在applicationContext.xml文件编写如下配置  --事务管理 Bean
        <!-- 定义事务管理bean -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <!-- 定义属性,声明事务规则 -->
        <tx:advice id="txAdvice" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="find*" read-only="true"></tx:method>
                <tx:method name="search*" read-only="true"></tx:method>
                <tx:method name="query*" read-only="true"></tx:method>
                <tx:method name="add*" propagation="REQUIRED"></tx:method>
                <tx:method name="del*" propagation="REQUIRED"></tx:method>
                <tx:method name="update*" propagation="REQUIRED"></tx:method>
                <tx:method name="do*" propagation="REQUIRED"></tx:method>
                <tx:method name="*" read-only="true" propagation="REQUIRED"></tx:method>
            </tx:attributes>
        </tx:advice>
    3.定义切面和切入点
        <aop:config>
            <!-- 定义切入点 -->
            <aop:pointcut id="pointcut" expression="execution(* cn.ssh.biz.imp.*.*(..))"></aop:pointcut>
            <!-- 定义切面 -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
        </aop:config>
    4.关于声明式事务中的一些机制
        1.事务传播机制 propagation
            1.REQUIRED      表示如果存在一个事务,则支持当前的事务,如果当前没有事务,则开启一个新的事务
            2.SUPPORTS    表示如果存在一个事务,则支持当前的事务,如果当前没有事务,则按非事务的方式执行
            3.MANDATORY    表示如果存在一个事务,则支持当前的事务;如果当前没有一个活动的事务,则抛出异常
            4.REQUIRES_NEW    表示总是开启一个新的事务.如果一个事务已经存在,则将存在的事务挂起,开启新事务执行该方法
            5.NOT_SUPPORTED表示总是以非事务方式执行,如果一个事务已经存在,则将这个存在的事务挂起,然后执行该方法
            6.NEVER        表示总是以非事务方式执行,如果当前的存在一活动的事务,则抛出异常
            7.NESTED    表示如果当前存在一个活动的事务,则创建一个事务作位当前的事务的嵌套事务运行,如果没有当前事务,则该取值与REQUIRED相同
        2.事务隔离等级    isolation    
            1.DEFAULT        表示使用数据库默认的事务隔离级别
            2.READ_UNCOMMITTED    未提交读
            3.READ_COMMITTED    提交读
            4.REPEATABLE_READ    可重复读
            5.SERIALIZABLE        串行读
        3.事务超时时间        timeout
        4.事务是否为只读    read-only
        5.设定能够触发回滚的异常类型 rollback-for
        6.设定不触发回滚的异常类型    no-rollback-for    
6.实现并配置Action
    1.创建Action类
        public class StudentAction extends ActionSupport{
            private Student student;            //当前Action类的Student实例
            private StudentBiz sb;                //当前Action依赖的业务逻辑接口
            //生路相应的get set方法
            public String login(){
                return SUCCESS;
            }
        }
    2.struts.xml配置文件
        1.最基本的配置信息
            <struts>
                <!-- 改变插件的自动装配策略 -->
                <constant name="struts.objectFactory.spring.autoWire" value="type"></constant>
                <package name="scott" namespace="/" extends="struts-deafult">
                    <action name="*Student" class="cn.ssh.action.StudentAction" method="{1}">
                        <result name="success">/{1}_success.jsp</result>
                        <result name="error">/{1}_error.jsp</result>
                    </action>
                </package>
            </struts>
        2.当属性的名字满足一定规则的时候.则无需在applicationContext.xml文件中配置Action Bean
        3.当属性的名字为自定义的时候,则需要在applicatioContext.xml文件中配置相应的Action Bean
            <bean id="studentAction" class="cn.ssh.action.StudentAction" scope="prototype">
                <property name="sb" ref="studentBiz"></property>      //当按照此定义Action Bean的时候,struts.xml文件中的<action class="studentAction">
            </bean>
=======================================================================SSH整合web.xml的配置=======================================================================
7.配置web.xml
    1.指定Spring配置文件的位置和初始化Spring容器
        <!-- 配置环境参数指定Spring配置文件的位置 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
        <!-- 配置Spring的ContextLoaderListener监听器,初始化Spring容器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    2.配置OpenSessionInViewFilter
        1.当SessionFactory的Id为sessionFactory的时候
            <filter>
                <filter-name>OpenSessionInViewFilter</filter-name>
                <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
            </filter>
            <filter-mapping>
                <filter-name>OpenSessionInViewFilter</filter-name>
                <url-pattern>*.action</url-pattern>
            </filter-mapping>
        2.当SessionFactory的Id不为sessionFactory的时候
            <filter>
                <filter-name>OpenSessionInViewFilter</filter-name>
                <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
                <init-param>
                    <param-name>sessionFactoryBeanName</param-name>
                    <param-value>前面自定义的SessionFactory Bean的Id名</param-value>
                </init-param>
            </filter>
            <filter-mapping>
                <filter-name>OpenSessionInViewFilter</filter-name>
                <url-pattern>*.action</url-pattern>
            </filter-mapping>
8.创建jsp页面
====================================================================================================================================================================
9.使用HibernateCallback实现自定义功能
    1.Object execute(HibernateCallback action) throws DataAccessException{}            //通用的指定回调函数的方法
    2.List executeFind(HibernateCallback action) throws DataAccessException{}        //该方法返回List结果集合
    //例子        --实现分页查询
    public List<Student> find(final int page,final int size){
        List<Student> list=getHibernateTemplate().executeFind(new HibernateCallback(){
            public Object doInHibernate(Session session) throws HibernateException,SQLException{
                Query query=session.createQuery("from Student");
                query.setFirstResult((page-1)*size);
                query.setMaxResults(size);
                return query.list();
            }
        });
    }
10.容器后置处理器    实现 BeanFactoryPostProcessor接口        Bean后置处理    实现BeanPostProcessor接口         
=================================================================配置数据源的其它方式=====================================================================
11.使用属性文件配置数据源
    <!--引入prperties文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>
    <!--配置datasource-->
    <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" value="datasource"></property>
    </bean>
11.使用JNDI配置数据源
    <bean id="datasource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/datasource"></property>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" value="datasource"></property>
    </bean>
=======================================================================任务调度配置=======================================================================
12.Spring-任务调度            //Quartz的三大核心:任务 调度器 触发器
    1.添加所需要的jar包 quartz-all-1.8.6.jar
    2.创建与任务相关的实体类
        public class Plan{
            private String date;        //会议的日期
            private String info;        //会议的内容
            //省略相应的get set
        }
    3.创建任务业务类-----类似于Dao和Biz类  //此处省略笔记
    4.创建任务类   实现Job接口
        public class RemindJob implements Job{
            private PlanBiz planBiz;
            @Override
            public void execute(JobExecutionContext context) throws JobExecutionContextException{
                planBiz.notice();                //执行公告的展示方法
            }
        }
    5.创建调度定时器任务类
        public class Test{
            public static void main(String[] args){
                //创建一个任务
                JobDetail jobDetail=new JobDetail("remindJob","group1",RemindJob.class);
                //创建一个触发器
                SimpleTrigger simTrigger=new SimpleTrigger("myTrigger",4,1000);            //4 为执行的次数   1000为执行相隔的时间为1秒
                simTrigger.setStartTime(new Date(System.currentTimeMillis()+1000));        //当程序运行后延迟一秒执行该任务调度
                //创建调度器
                SchedulerFactory schedulerFactory=new SchedulerFactory();
                Scheduler scheduler=schedulerFactory.getScheduler();
                //将任务和触发器进行绑定
                scheduler.schedulerJob(jobDetail,);
            }
        }

   
0 0
原创粉丝点击