Spring类型转换系统对于boolean类型进行了容错处理,除了可以使用“true/false”标准的Java值进行注入,还能使用“yes/no”、“on/off”、“1/0”来代表“真/假”。
1.创建BooleanBean类:
package com.spring.pojo;
//boolean 类型
public class BooleanBean {
private boolean success;
@Override
public String toString() {
return "BooleanBean [success=" + success + "]";
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
2.创建Bean配置spring-booleanInject.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- boolean 参数值可以用on/off 来代表真/假 -->
<bean id="booleanBean" class="com.spring.pojo.BooleanBean">
<property name="success" value="on" />
</bean>
<!--boolean参数可以用yes/no 来表示真/假 -->
<bean id="booleanBean1" class="com.spring.pojo.BooleanBean">
<property name="success" value="no" />
</bean>
<!-- boolean参数可以用 1/0来表示真/假 -->
<bean id="booleanBean2" class="com.spring.pojo.BooleanBean">
<property name="success" value="0" />
</bean>
</beans>
3.创建BooleanTest测试类:
package com.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.pojo.BooleanBean;
public class BooleanTest {
@SuppressWarnings("resource")
@Test
public void BooleanTest(){
ApplicationContext act=new ClassPathXmlApplicationContext("spring-booleanInject.xml");
BooleanBean boolea=act.getBean("booleanBean", BooleanBean.class);
System.out.println("on/off :"+boolea.toString());
BooleanBean boolea1=act.getBean("booleanBean1", BooleanBean.class);
System.out.println("yes/no :"+boolea1.toString());
BooleanBean boolea2=act.getBean("booleanBean2", BooleanBean.class);
System.out.println("1/0 :"+boolea2.toString());
}
}
4.测试结果:
on/off :BooleanBean [success=true]
yes/no :BooleanBean [success=false]
1/0 :BooleanBean [success=false]