发表于: 2016-09-18 12:22:21

2 2141


一、今天完成
基于spring+JDBC的数据库查询
1)xml配置
bean.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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--加载外部属性文件-->
<bean class="task2.placeHolder.EncryptPropertyPlaceholderConfigurer"
     p:location="classpath:Config/jdbc.properties"
     p:fileEncoding="utf-8"/>
<!--声明JdbcTemplateDemo,用于调用JdbcTemplateBean-->
<bean id="jdbcTemplateDemo" class="task2.dao.JdbcTemplateDemo" >
   <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!--声明BasicDataSource类,加载JDBC连接配置-->
<bean id="dataSource"
     class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close"
     p:driverClassName="${driverClassName}"
     p:url="${url}"
     p:username="${userName}"
     p:password="${passWord}"/>
<!--声明JdbcTemplateBean-->
<bean id="jdbcTemplate"
     class="org.springframework.jdbc.core.JdbcTemplate"
     p:dataSource-ref="dataSource"/>
</beans>
jdbc.properties中
driverClassName=com.mysql.jdbc.Driver
dataBase=codetrainclass
url=jdbc:mysql://192.168.1.254:3306/${dataBase}
#数据库帐密用DES加密后保存
userName=gd+k55t6VVQ=
passWord=gd+k55t6VVQ=
密文工具placeHolder.DESUtils.java中
public class DESUtils {
  /**
   * 指定密钥
   */
  private static Key key;
  private static String KEY_STR = "oyyd";
  static {
     try {
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        generator.init(new SecureRandom(KEY_STR.getBytes()));
        key = generator.generateKey();
        generator = null;
     } catch (Exception e) {
        throw new RuntimeException(e);
     }
  }
  /**
   * str进行DES加密
   *
   * @param str
   * @return
   */
  public static String getEncryptString(String str) {
     BASE64Encoder base64en = new BASE64Encoder();
     try {
        byte[] strBytes = str.getBytes("UTF8");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptStrBytes = cipher.doFinal(strBytes);
        return base64en.encode(encryptStrBytes);
     } catch (Exception e) {
        throw new RuntimeException(e);
     }
  }
  /**
   * str进行DES解密
   *
   * @param str
   * @return
   */
  public static String getDecryptString(String str) {
     BASE64Decoder base64De = new BASE64Decoder();
     try {
        byte[] strBytes = base64De.decodeBuffer(str);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptStrBytes = cipher.doFinal(strBytes);
        return new String(decryptStrBytes, "UTF8");
     } catch (Exception e) {
        throw new RuntimeException(e);
     }
  }
  public static void main(String[] args) throws Exception {
     BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
     String     username = null,
           password = null,
           line = null;
     Boolean yn = true;
     while (yn) {
        System.out.println("请输入请输入username:");
        username = bufr.readLine();
        System.out.println("password:");
        password = bufr.readLine();
        System.out.println("输入的 username=" + username + " password=" + password + " (Y/N)");
        line = bufr.readLine();
        if("Y".equalsIgnoreCase(line) || "y".equalsIgnoreCase(line))
           break;
     }
     if (username != null && !"".equals(username))
        System.out.println("username通过DES加密为:" + getEncryptString(username));
     if (password != null && !"".equals(password))
        System.out.println("password通过DES加密为:" + getEncryptString(password));
  }
}
调用密文工具类placeHolder.DESUtils.java中
/**
* 继承PropertyPlaceholderConfigurer支持密文的属性配置器
*/
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
  private String[] encryptPropNames ={"userName","passWord"};
  //对特定属性的值进行转换
  @Override
  protected String convertProperty(String propertyName, String propertyValue) {    
     if(isEncryptProp(propertyName)){
        String decryptValue = DESUtils.getDecryptString(propertyValue);
        System.out.println(decryptValue);
        return decryptValue;
     }else{
        return propertyValue;
     }
  }
  /**
   * 判断是否是加密的属性
   * @param propertyName
   * @return
   */
  private boolean isEncryptProp(String propertyName){
     for(String encryptPropName:encryptPropNames){
        if(encryptPropName.equals(propertyName)){
           return true;
        }
     }
     return false;
  }
}
dao.JdbcTemplateDemo中
public class JdbcTemplateDemo {
   private JdbcTemplate jdbcTemplate;
   public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
       this.jdbcTemplate = jdbcTemplate;
   }
   public List<Enroll> getStudents(){
       String sql = "SELECT * FROM enroll;";
       final List<Enroll> students = new ArrayList<Enroll>();
       jdbcTemplate.query(sql, new RowCallbackHandler() {
//匿名内部类实现RowCallbackHandler接口
           public void processRow(ResultSet resultSet) throws SQLException {
               Enroll enroll = new Enroll();
               enroll.setStudent_id(resultSet.getInt("student_id"));
               enroll.setStudent_name(resultSet.getString("student_name"));
               enroll.setCreate_time(resultSet.getLong("create_time"));
               enroll.setUpdate_time(resultSet.getLong("update_time"));
               enroll.setMobile_num(resultSet.getString("mobile_num"));
               students.add(enroll);
           }
       });
       return students;
   }
}
app.domain中
public static void main(String[] args) {
   ApplicationContext ctx = new ClassPathXmlApplicationContext("Config/bean.xml");
   JdbcTemplateDemo jdbcTemplateDemo = (JdbcTemplateDemo) ctx.getBean("jdbcTemplateDemo");
   System.out.println(jdbcTemplateDemo.getStudents());

}


2)XML+注解
bean_annotation.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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--激活注解-->
<context:annotation-config />
<!--扫描包及注册注解声明的Bean-->
<context:component-scan base-package="task2.dao.impl"/>
<!--加载配置文件-->
<bean class="task2.placeHolder.EncryptPropertyPlaceholderConfigurer"
     p:location="classpath:Config/jdbc.properties"
     p:fileEncoding="utf-8"/>
<!--声明BasicDataSource类,加载JDBC连接配置-->
<bean id="dataSource"
     class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close"
     p:driverClassName="${driverClassName}"
     p:url="${url}"
     p:username="${userName}"
     p:password="${passWord}"/>
<!--声明JdbcTemplateBean-->
<bean id="jdbcTemplate"
     class="org.springframework.jdbc.core.JdbcTemplate"
     p:dataSource-ref="dataSource"/>
</beans>
dao.JdbcTemplate2中
@Repository("jdbcTemplate2")
public class JdbcTemplate2 {
   @Resource(name = "jdbcTemplate")
   private JdbcTemplate jdbcTemplate;

...


二、明天计划
1.基于Spring+Mybatis实现数据库查询

2.学习SpringMVC相关知识


三、遇到问题
1.各种空指针异常,主要集中在没有把bean.xml中的元素间没有按照.java文件的调用需求串起来。
2.使用 p: 的时候没有在 <beans xmlns="http:/... 完成xmlns配置的引入,导致无法识别 p: 。
3.<context:property-placeholder location="classpath*:Config/jdbc.properties"/> 的外部文件加载方式,仍不能成功将属性加载进来。
4.@Autowired、@Qualifier未正常被识别,百度:未使用<context:annotation-config />激活

5.@Repository未正常被识别,百度:未使用<context:component-scan base-package="task2.dao.impl"/>激活


四、收获
花了2天学习《Spring 3.x企业应用开发实战》对Spring-IOC,对基于xml配置的注入代码实现流程有了一定的了解,通过一个JDBC的数据库查询实现了访问。



返回列表 返回列表
评论

    分享到