美文网首页
Spring基础

Spring基础

作者: stutterr | 来源:发表于2017-07-31 17:46 被阅读10次
    1. 引入
    • 将Spirng相关的包都copy到lib目录下
    • 在原web.xml 文件下配置contextConfig文件
    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    

    当前上下文配置文件目录是在src下

    • 在原web.xml文件下配置listener,也就是当我们的应用程序已启动就会执行listener-class中的方法
    <listener>
       <display-name></display-name>
       <listener-class>org.spirngframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    这个启动方法就会去解析我们的contextConfig文件。

    2. 在util包下创建SpringUtil class

    工厂模式引入

    • 代码
    public class SpringUtil implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext = null;
        @Override
        public void setApplicationContext(ApplicationContext ac)  //beanFactory 通过这个类可以取到配置文件的东西
                throws BeansException {
            applicationContext = null;
            
        }
        
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
        
        public static Object getBean(String beanId) {
            ApplicationContext applicationContext = getApplicationContext();
            return applicationContext.getBean(beanId);
        }
    }
    

    这边的ApplicationContext类相当于一个beanFactory.用来获取bean.xml中的配置。

    • 加入到xml中
      <bean class="com.xxx.xxx.util.SpringUtil"></bean>
    3. Spring中的JdbcTemplate使用方法
    • applicationContext.xml 中读取数据库配置路径等并且配置数据源
      • 读取配置文件
          <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
           <property name="locations">
               <list>  <!-- classpath 是该文件路径-->
                   <value>classpath:app.properties</value>  
               </list>  
           </property>  
       </bean>  
      
      *设置数据源 连接池
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
            <property name="driverClass" value="${jdbc.driver}" /> 
            <property name="jdbcUrl" value="${jdbc.url}" /> 
            <property name="user" value="${jdbc.user}" /> 
            <property name="password" value="${jdbc.password}" /> 
            <property name="maxPoolSize" value="20" /> 
            <property name="minPoolSize" value="5" /> 
            <property name="acquireIncrement" value="3" /> 
            <property name="initialPoolSize" value="5" /> 
        </bean>
      

    initialPoolSize 初始化产生的数量
    acquireIncrement 访问量增大时连接每次增大的数量
    minPoolSize 最小数量
    maxPoolSize 最大数量

    *设置JDBCTemplate

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

    之后在DAO中定义,并且设置set方法已供spring注入. 注意,导入的包应该在spring下

        private JdbcTemplate jdbcTemplate;
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    

    *使用

           String sql = "SELECT * FROM user WHERE user_name= ?";
           Object[] args = new Object[] {userName};  //准备参数
           
           //每行处理,rsToObject
           RowMapper<User> rowMapper = new RowMapper<User>() {
    
               @Override
               public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                   User user = new User();
                   user.setId(rs.getInt(1));
                   user.setUserName(rs.getString("user_name"));
                   user.setPassword(rs.getString("password"));
                   return user;
               }
           };
           return jdbcTemplate.queryForObject(sql, args, rowMapper);
    

    注意事项,请确保每个注入类都有set方法和被注入类有无参数的构造函数。

    查询基本结构

            String sql = "SELECT * FROM question WHERE id= ?";
            Object [] args = new Object[] {questionId};
    
            RowMapper<Question> rowMapper =new RowMapper<Question>(){
                @Override
                public Question mapRow(ResultSet rs, int rowNum)
                        throws SQLException {
                    Question question = new Question();
                    question = new Question();
                    question.setId(rs.getInt(1));
                    question.setDisplayId(rs.getString("display_id"));
                    question.setDescription(rs.getString("description"));
                    question.setQuestionOptionList(findQuestionOptionByQuestionId(questionId));
                    return question;
                }
            };
    
            return jdbcTemplate.queryForObject(sql, args,rowMapper);
    

    Object [] args放置查询参数
    RowMapper 用来获取构建查询结果
    queryForObject 返回一个实例,如果多条查询用query
    插入update 删除excute(),

    如何返回插入后返回主键id?

            final String sql = "Insert INTO question(display_id, description, created_time, updated_time)"+
                    "VALUES(?, ?, NOW(), NOW())";
            KeyHolder keyHolder = new GeneratedKeyHolder();
    
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection con)
                        throws SQLException {
                    PreparedStatement preState=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                    preState.setString(1,question.getDisplayId());
                    preState.setString(2,question.getDescription());
                    return preState;
                }
            }, keyHolder);
            question.setId(keyHolder.getKey().intValue());
    

    定义一个keyHolder 并且使用PreparedStatementCreator来获取自增ID。

    4. 申明式事务配置
    • 首先定义事务管理器
       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
           <property name="dataSource" ref="dataSource"></property>
       </bean>
    
    • 定义advice
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="saveQuestion" propagation="REQUIRED" read-only="false"/>
                <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
            </tx:attributes>
        </tx:advice>
    

    在被写上propagation="REQUIRED" read-only="false"会启动事务管理器
    rollback-for 代表发生什么异常时回滚 。默认时runtimeException 所以我们要将一些exception都换成runtimeException

    • 设置aop
      aop:pointcut代表在那个层
      第一个中代表所有访问类型(public private)
      第二个代表包
      第三个代表service下所有的包
      第四个
      代表所有的方法

    aop:advisor切面中加上通知。

        <aop:config>
           <aop:pointcut expression="execution(* com.gavin.exam.service..*.*(..))" id="pc"/>
           <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" order="1"/>
       </aop:config>
    

    相关文章

      网友评论

          本文标题:Spring基础

          本文链接:https://www.haomeiwen.com/subject/njmclxtx.html