set注入
public class MyTime {
private Date date;
public String getNowTime (){
return "现在时间是:" +this .date.toLocaleString();
}
public void setDate (Date date) {
this .date = date;
}
}
XML
<bean id ="userDao" class ="com.qu.dao.impl.UserDAOImpl" ></bean>
<bean id ="mytime" class ="com.qu.spring.ioc.MyTime" >
<property name ="date" ref ="mydate" ></property >
</bean>
<bean id ="mydate" class ="java.util.Date" ></bean>
构造方式
@Resource (name="mytime1" )
private MyTime myTime1 = null ;
public MyTime (Date date){
this .date=date;
}
XML
<bean id ="mydate" class ="java.util.Date" > </bean >
<bean id ="mytime1" class ="com.qu.spring.ioc.MyTime" >
<constructor-arg name ="date" ref ="mydate" > </constructor-arg >
</bean >
P标签写法
public class MyTime {
private Date date;
private String username;
public String getNowTime (){
return this .username +this .date.toLocaleString();
}
public void setDate (Date date) {
this .date = date;
}
public void setUsername (String username) {
this .username = username;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns ="http://www.springframework.org/schema/beans"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p ="http://www.springframework.org/schema/p"
xsi:schemaLocation ="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id ="mytime" class ="com.qu.spring.ioc.MyTime" p:date-ref ="mydate" p:username ="张三" >
</bean >
<bean id ="mydate" class ="java.util.Date" > </bean >
</beans >
date-ref之后添加"-ref"后缀表示是对另外一个bean的引用。