1.首先附上我的eclipse中創建Spring項目的目錄結構:
2.Spring推薦使用接口,首先定義兩個接口:IDao 和IService
IDao接口:
package com.spring.inter;
public interface IDao {
public String sayHello(String name);
}
IService接口:
package com.spring.inter;
public interface IService {
public void service(String name);
}
3.建立接口的實現類:
DaoImpl:
package com.spring.impl;
import java.util.Calendar;
import com.spring.inter.IDao;
public class DaoImpl implements IDao {
@Override
public String sayHello(String name) {
// TODO Auto-generated method stub
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(hour<6)
return "凌晨好,"+name;
if(hour<12)
return "早上好,"+name;
if(hour<13)
return "中午好,"+name;
if(hour<16)
return "下午好,"+name;
return "晚上好,"+name;
}
}
ServiceImpl:
public class ServiceImpl implements IService {
private IDao idao;
@Override
public void service(String name) {
System.out.println(idao.sayHello(name));
}
public IDao getIdao() {
return idao;
}
public void setIdao(IDao idao) {
this.idao = idao;
}
}
4.然後對Spring的配置文件applicationContext.xml進行配置:
<?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-3.0.xsd">
<bean id="daoImpl" class="com.spring.impl.DaoImpl"></bean>
<bean id="serviceImpl" class="com.spring.service.ServiceImpl">
<property name="idao" ref="daoImpl"></property>
</bean>
</beans>
5.建立測試類:
package com.spring.junit;
import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.spring.inter.IService;
public class test1 {
@Test
public void test()
{
XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("applicationContext.xml"));
IService hello =(IService) factory.getBean("serviceImpl");
hello.service("HelloBean");
factory.destroySingletons();
}
}
輸出結果爲:早上好,HelloBean
早上好,HelloBean