戴着假发的程序员出品
property标签
spring应用手册(第一部分)
property是用来给bean的属性配置要注入的值的。这些值可以是bean或者简单值(基本类型和Stirng)。
案例:
/**
* @author 戴着假发的程序员
* @description
*/
public class AccountService {
private IAccountDAO accountDAO;
private String appName;
public void setAppName(String appName) {
this.appName = appName;
}
public void setAccountDAO(IAccountDAO accountDAO) {
this.accountDAO = accountDAO;
}
public int save(String name){
System.out.println("AppName:"+appName);
System.out.println("AccountService-save->保存用户:"+name);
return accountDAO.save(name);
}
}
AccountService中需要注入属性IAccountDAO和appName,我们可以按照下面的方式注入:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byType" 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">
<!-- 注册accountDAO_oracle -->
<bean id="accountDAO_oracle" class="com.dk.demo1.dao.impl.AccountDAO_oracle"/>
<!-- 注册accountService 注入accountDAO_mysql -->
<bean id="accountService" name="a_service"
class="com.dk.demo1.service.AccountService">
<property name="accountDAO" ref="accountDAO_oracle"/>
<!-- 注入简单属性 -->
<property name="appName" value="spring应用手册"/>
<!-- <property name="appName">-->
<!-- <value>spring应用手册</value>-->
<!-- </property>-->
</bean>
</beans>
这样的配置可以让我们从spring容器中获取的accountService对象已经装配好了上面的两个属性。
测试:
@Test
public void testSpringProperty(){
//创建spring容器
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = ac.getBean(AccountService.class);
accountService.save("戴着假发的程序员");
}
控制台: