Common BeanUtils组件的使用(源码)

Common BeanUtils组件方便了对JavaBean的使用。其中的一些类方法,使我们使用JavaBean得到了便利。

 

使用Common BeanUtils组件需要三个Jar包,分别是

commons-beanutils-1.8.0-BETA.jar

commons-logging-1.1.1.jar

commons-logging-api-1.1.1.jar

 

可从官网下载,不过为了方便,我把三个包传上来。点击下载

 

下面用四个例子说明该组件的三个优点。

 

例子一:

创建三个Java文件,分别为

Address.java

Profile.java

User.java

 

在写一个类文件递进调用函数,命名:BeanUtilsExample1.java,源码:

 


package com.sy;

import java.util.Map;
import java.util.HashMap;
import java.util.GregorianCalendar;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanUtilsExample1 {
    private User prepareData() {
        Profile profile = new Profile();
        profile.setEmail("[email protected]");
        profile.setBirthDate(new GregorianCalendar(3212910).getTime());
        Map<String, String> phone = new HashMap<String, String>();
        phone.put("home""11011011");
        phone.put("office""82826905");
        profile.setPhone(phone);
        Address[] address = new Address("中国""北京""100120""天安门北大街888号"),
                new Address("中国""广州""100120""石牌村666号") }
;
        profile.setAddress(address);

        User user = new User();
        user.setUserId(new Long(123456789));
        user.setUsername("shiyang");
        user.setPassword("12345");
        user.setProfile(profile);
        return user;
    }


    public static void main(String[] args) {
        BeanUtilsExample1 example = new BeanUtilsExample1();
        User user = example.prepareData();
        try {
            System.out.println("输出对象的属性值---------------------------------");
            System.out.println(BeanUtils.getProperty(user, "userId"));
            System.out.println(BeanUtils.getProperty(user, "username"));//返回字符型
            System.out.println(PropertyUtils.getProperty(user, "username"));//返回对象类型
            System.out.println(BeanUtils.getProperty(user, "profile.email"));//重点
            System.out
                    .println(BeanUtils.getProperty(user, "profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.phone(home)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.phone(office)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.address[0].city"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.address[1].city"));//重点

            User user2 = new User();
            BeanUtils.copyProperties(user2, user);
            //两层拷贝,基本类型复制值,对于引用类型(除String,封装类型外)复制地址值。
            System.out.println("输出复制属性的属性值-------------------------------");
            System.out.println(BeanUtils.getProperty(user, "username"));
            System.out
                    .println(BeanUtils.getProperty(user, "profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.phone(home)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.address[0].addr"));//重点

            System.out.println("输出复制属性修改以后的属性值---------------------");
            BeanUtils.setProperty(user2, "userId"new Long(8888888));
            PropertyUtils.setProperty(user2, "username""ahah");
            BeanUtils.setProperty(user2, "profile.email""[email protected]");//重点
            BeanUtils.setProperty(user2, "profile.birthDate",//重点
                    new GregorianCalendar(190025).getTime());
            BeanUtils.setProperty(user2, "profile.address[0]"new Address(
                    "中国""深圳""600600""深北大道111号"));//重点
            System.out.println(BeanUtils.getProperty(user2, "userId"));
            System.out.println(BeanUtils.getProperty(user2, "username"));
            System.out.println(BeanUtils.getProperty(user2, "profile"));
            System.out.println(BeanUtils.getProperty(user2, "profile.email"));//重点
            System.out.println(BeanUtils
                    .getProperty(user2, "profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user2,
                    "profile.address[0].city"));//重点

            System.out.println("与被复制属性值的对象的比较-------------------------------");
            System.out.println(BeanUtils.getProperty(user, "userId"));
            System.out.println(BeanUtils.getProperty(user, "username"));
            System.out.println(BeanUtils.getProperty(user, "profile"));
            System.out.println(BeanUtils.getProperty(user, "profile.email"));//重点
            System.out
                    .println(BeanUtils.getProperty(user, "profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    "profile.address[0].city"));//重点
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

从中可以看出,

调用一个属性中的方法,只需要加一个“.”即可。精简了操作。

还可以拷贝属性,但要注意是二层拷贝。

还要注意BeanUtils和PropertyUtils的区别。

 

例子二:

动态创建属性

文件名:BeanUtilsExample2,源码:

 


package com.sy;

import java.util.GregorianCalendar;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.beanutils.BeanUtils;

public class BeanUtilsExample2 {
    //动态创建属性
    public static void main(String args[]) throws Exception {

        LazyDynaBean hh = new LazyDynaBean();
        hh.set("country""中国");
        hh.set("city""北京");
        hh.set("postCode""100120");
        hh.set("addr""aaaaaaa");

        LazyDynaBean bb = new LazyDynaBean();
        bb.set("phone""home""11011011");
        bb.set("phone""office""111111");
        bb.set("email""[email protected]");
        bb.set("address"0, hh);
        bb.set("birthDate"new GregorianCalendar(1990329).getTime());

        LazyDynaBean tt = new LazyDynaBean();
        tt.set("userId"new Long(8888888));
        tt.set("gggg""施杨");
        tt.set("password""sgsgsgsg");
        tt.set("dddd", bb);

        System.out.println(BeanUtils.getProperty(tt, "gggg"));
        System.out.println(BeanUtils.getProperty(tt, "dddd.birthDate"));
        System.out.println(BeanUtils.getProperty(tt,
                "dddd.address[0].addr"));
        System.out
                .println(BeanUtils.getProperty(tt, "dddd.phone(office)"));
    }

}

 

例子三:

连接Mysql数据库

文件名BeanUtilsExample3.java源码:

 


package com.sy;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;

public class BeanUtilsExample3 {
    public static void main(String args[]) throws Exception {
        Connection conn = getConnection();
        PreparedStatement ps = conn
                .prepareStatement("select id,title,time from guestbook2 order by id desc");
        ResultSet rs = ps.executeQuery();

        ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);//重点,二次封装,对连接对象有依赖
        Iterator itr = rsdc.iterator();
        while (itr.hasNext()) {
            DynaBean bean = (DynaBean) itr.next();
            System.out.print(bean.get("id") + "\t");
            System.out.print(bean.get("title") + "\t");
            System.out.println(bean.get("time"));
        }

        conn.close();
    }


    private static Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/guestbook";
        String username = "root";
        String password = "hicc";
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        }
 catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

}

 

例子四:

文件BeanUtilsExample4.java,源码:

 


package com.sy;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.RowSetDynaClass;

public class BeanUtilsExample4 {
    public static void main(String args[]) throws Exception {
        Connection conn = getConnection();
        PreparedStatement ps = conn
                .prepareStatement("select id,title,time from guestbook2 order by id desc");
        ResultSet rs = ps.executeQuery();

        RowSetDynaClass rsdc = new RowSetDynaClass(rs);
        //重点,与ResultSetDynaClass的区别
        conn.close();//重点,关闭连接后仍能读取
        Iterator itr = rsdc.getRows().iterator();
        while (itr.hasNext()) {
            DynaBean bean = (DynaBean) itr.next();
            System.out.print(bean.get("id") + "\t");
            System.out.print(bean.get("title") + "\t");
            System.out.println(bean.get("time"));
        }

    }


    private static Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/guestbook";
        String username = "root";
        String password = "hicc";
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        }
 catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

}

 

这就是Common BeanUtils组件的主要应用!!!

 

施杨出品!!!

 

这篇随笔意义非凡,这是团队博客的第800篇哦。

 

 


作者:施杨(施杨's Think out)
出处:http://shiyangxt.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 

你可能感兴趣的:(mysql,jdbc,String,user,url,Office)