### 作用
注入基本类型和String和其它bean类型 【常用】
涉及的标签:property
出现的位置:bean标签的内容
标签的属性
- name:指定注入时所调用的set方法名称 【不是成员变量名称】
- value:提供基本类型个String类型的数据
- ref:引用其他的bean类型数据或bean对象,即在spring的IOC核心容器中出现过的bean对象
特点
-
创建对象时没有明确的限制,可以直接使用默认构造函数
-
如果某个成员必须有值,则获取对象时set方法可能没有执行到,整个程序就结束了
可能刚调用构造函数,就执行完了,没有到set这一步
代码:
<?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">
<!--Set方法注入 【常用】-->
<bean id="asSet" class="cn.luis.service.impl.AccountServiceImplSet">
<property name="userame" value="钢铁侠"></property>
<property name="age" value="35"></property>
<property name="birthday" ref="now"></property>
</bean>
<!--配置一个日期对象-->
<!--spring读取全限定类名,反射创建对象,并存入spring核心容器中 -->
<bean id="now" class="java.util.Date"></bean>
</beans>
AccountServiceImplSet
package cn.luis.service.impl;
import cn.luis.service.IAccountService;
import java.util.Date;
public class AccountServiceImplSet implements IAccountService {
/**
* 若是经常变化的方式,并不适用于注入的方式
*/
private String name;
private Integer age;
private Date birthday;
public void setUserame(String name) { // set方法名称【不一定是成员变量名称】
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public void saveAccount(){
System.out.println("servlce中的saveAccount方法执行了..."+name+","+age+","+birthday);
}
}
Client
package cn.luis.ui;
import cn.luis.dao.IAccountDao;
import cn.luis.service.IAccountService;
import cn.luis.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Client {
public static void main(String[] args) {
// 1.获取核心容器对象 【容器】
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.根据【bean的id】获取Bean对象
IAccountService as = (IAccountService) ac.getBean("asSet");
as.saveAccount();
}
}
结果:
servlce中的saveAccount方法执行了...钢铁侠,35,Tue Mar 10 22:16:12 CST 2020