BeanUtils简化setter注入

在java中,我们经常通过在类中定义属性的get和set方法,然后通过set方法为属性赋值。但是,在一些情况下,我们需要动态访问对象的属性(不知道属性的get和set的情况下)。比如如下的情况:

  • 使用基于xml的资源(tomcat的server.xml文件)

Java提供了Reflection(反射)和Introspection(内省)的API,不过这些api操作起来都比较麻烦,BeanUtils 提供了易于使用的包装器。
BeanUtils是Apache Commons项目下的一个组件,具体请看官网-Commons BeanUtils

使用

添加依赖


    commons-beanutils
    commons-beanutils
    1.9.3

实体类

public class PetStore {
    private AccountDao accountDao;
    private ItemDao itemDao;
    private String env;
    private int version;

    public AccountDao getAccountDao() {
        return accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public ItemDao getItemDao() {
        return itemDao;
    }

    public void setItemDao(ItemDao itemDao) {
        this.itemDao = itemDao;
    }

    public String getEnv() {
        return env;
    }

    public void setEnv(String env) {
        this.env = env;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }
}

setProperty方法API

BeanUtils.setProperty(bean,propertyName,propertyValue);
bean - 操作的队形
propertyName- 属性名称
propertyValue- 赋予的属性值

测试

@Test
public void testSetterUseBeanUtis() throws InvocationTargetException, IllegalAccessException {
        PetStore store = new PetStore();
        BeanUtils.setProperty(store ,"version","1");
        System.out.println(store .getVersion());  //1
    }

使用BeanUtils都不用我们自己做数据类型转换了。

你可能感兴趣的:(BeanUtils简化setter注入)