Java后端避坑——属性为Boolean的gettter方法和is方法同时存在违反JavaBean规范

3,513 阅读1分钟

在做用户登录的时候,通常我们会判断当前账号是否可用,将这个属性设置为Boolean类型。而我们定义好的JavaBean需要实现UserDetails 接口来规范用户属性,然后重写里面的方法来判断当前的用户是否可用。这时候重写的is方法就会跟Mybatis自动生成的getter方法同时存在。如下面的实例程序。

定义一个普通的Bean:

public class Hr implements UserDetails {
    private Boolean enabled;//账号是否可用
    public String getEnabled() {
        return enabled;
    }
    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }
    **
     * 账户是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

程序编译时出现的错误如下:

o.m.spring.mapper.MapperFactoryBean : Error while adding the mapper 'interface com.chb.vhr.mapper.HrMapper' to configuration. org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/chb/vhr/mapper/HrMapper.xml'. Cause: org.apache.ibatis.reflection.ReflectionException: Illegal overloaded getter method with ambiguous type for property enabled in class class com.chb.vhr.bean.Hr. This breaks the JavaBeans specification and can cause unpredictable results.

llegal overloaded getter method with ambiguous type for property enabled in class class com.chb.vhr.bean.Hr.
(该语句的意思是:Hr类中启用的属性类型不明确,非法重载getter方法)
因为isEnable相当于getEnable,导致JavaBean里面有两个getEnabled方法,违反了JavaBean的规范,只要将其中一个删掉就可以了。

积少成多,滴水穿石!