spring boolean类型注入

本文介绍Spring类型转换系统对于boolean类型的容错处理机制,通过创建BooleanBean类并配置相应的XML文件,展示了如何使用'on/off'、'yes/no'、'1/0'等不同方式来表示真假值,并提供了实际的测试类验证效果。

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]

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值