戴着假发的程序员 出品
spring应用手册(第一部分)
我们在使用property和constructor-arg为bean注入属性时,如果属性是简单类型,我们可以通过value直接注入。这里简单类型主要是指java的基本类型和String类型。
案例:
我们有一个Service类:
/** * @author 戴着假发的程序员 * * @description */ public class AccountService { private String appName; private int count; public void setAppName(String appName) { this.appName = appName; } public void setCount(int count) { this.count = count; } //无参数构造 public AccountService(){} //有参数构造 public AccountService(String appName,int count){ this.appName = appName; this.count = count; } @Override public String toString(){ return "appName:"+appName+";\r\ncount:"+count; } }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); }结果:
appName:假发; count:100 appName:程序员; count:1000000 appName:戴假发; count:999 appName:有假发; count:99