直接上圖:

源碼:
HelloDao.java
package www.csdn.spring.dao;
public interface HelloDao {
public void sayHello();
}
HelloDAoImpl.java
package www.csdn.spring.dao;
public class HelloDaoImpl implements HelloDao{
public HelloDaoImpl() {
System.out.println("HelloDaoImpl實例化.......");
}
@Override
public void sayHello() {
System.out.println("say:hello");
}
}
DemoTest.java
package www.csdn.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import www.csdn.spring.dao.HelloDao;
import www.csdn.spring.dao.HelloDaoImpl;
import www.csdn.spring.service.HelloService;
public class DemoTest {
@Test
public void test(){
HelloDao helloDao = new HelloDaoImpl();
helloDao.sayHello();
/*// 容器創建 實例化容器
// 讀取 classes 路徑下面的文件 參數 動態參數、單個參數、數組 等
ApplicationContext context = new ClassPathXmlApplicationContext(
"spring.xml");
// HelloDao helloDao = (HelloDao) context.getBean("helloDaoImpl");
//HelloDao helloDao =context.getBean("helloDaoImpl", HelloDao.class);
HelloDaoImpl helloDaoImpl =context.getBean("helloDaoImpl", HelloDaoImpl.class);
//helloDao.sayHello();
//helloSerivceImpl
HelloService helloService = context.getBean("helloServiceImpl", HelloService.class);
helloService.sayHello();*/
}
}
spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- spring容器 就是負責創建、管理、維護Bean 並且能夠依賴注入到相應組件上 -->
<bean id="helloDaoImpl" class="www.csdn.spring.dao.HelloDaoImpl" scope="singleton" lazy-
init="default"></bean>
</beans>
spring-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloServiceImpl" class="www.csdn.spring.service.HelloServiceImpl" scope="singleton" lazy-
init="false">
<property name="helloDao" ref="helloDaoImpl" />
</bean>
</beans>
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />
</beans>
執行測試類之後控制台輸出
HelloDaoImpl實例化.......
say:hello