1.24 value注入简单数据
戴着假发的程序员出品
[查看视频教程]
我们在使用property和constructor-arg为bean注入属性时,如果属性是简单类型,我们可以通过value直接注入。
这里简单类型主要是指java的基本类型和String类型。
案例:
我们有一个Service类:
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 public class AccountService { 7 private String appName; 8 private int count; 9 public void setAppName(String appName) { 10 this.appName = appName; 11 } 12 public void setCount(int count) { 13 this.count = count; 14 } 15 //无参数构造 16 public AccountService(){} 17 //有参数构造 18 public AccountService(String appName,int count){ 19 this.appName = appName; 20 this.count = count; 21 } 22 @Override 23 public String toString(){ 24 return "appName:"+appName+";\r\ncount:"+count; 25 } 26 }
AccountService有两个简单类型的属性,我们可以通过下面的方式注入属性:
<?xml version="1.0" encoding="UTF-8"?> <beans default-autowire="byName" 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"> <!-- accountService 方式1 --> <bean id="accountService1" class="com.dk.demo1.service.AccountService"> <property name="appName" value="假发"/> <property name="count" value="100"/> </bean> <!-- accountService 方式2 --> <bean id="accountService2" class="com.dk.demo1.service.AccountService"> <property name="appName"><value>程序员</value></property> <property name="count"><value>1000000</value></property> </bean> <!-- accountService 方式3 --> <bean id="accountService3" class="com.dk.demo1.service.AccountService"> <constructor-arg name="appName" value="戴假发"/> <constructor-arg name="count" value="999"/> </bean> <!-- accountService 方式4 --> <bean id="accountService4" class="com.dk.demo1.service.AccountService"> <constructor-arg name="appName"> <value>有假发</value> </constructor-arg> <constructor-arg name="count"> <value>99</value> </constructor-arg> </bean> </beans>
测试:
@Test public void testValue(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService bean1 = (AccountService) ac.getBean("accountService1"); AccountService bean2 = (AccountService) ac.getBean("accountService2"); AccountService bean3 = (AccountService) ac.getBean("accountService3"); AccountService bean4 = (AccountService) ac.getBean("accountService4"); System.out.println(bean1); System.out.println(bean2); System.out.println(bean3); System.out.println(bean4); }
结果:
1 appName:假发; 2 count:100 3 appName:程序员; 4 count:1000000 5 appName:戴假发; 6 count:999 7 appName:有假发; 8 count:99
我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员