
package www.csdn.spring.dao;
public interface HelloDao {
void sayHello();
}
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");
}
}
package www.csdn.spring.service;
public interface HelloService {
void sayHello();
}
package www.csdn.spring.service;
import www.csdn.spring.dao.HelloDao;
public class HelloServiceImpl implements HelloService {
private HelloDao helloDao; // 由容器注入
public void setHelloDao(HelloDao helloDao) {
this.helloDao = helloDao;
}
@Override
public void sayHello() {
helloDao.sayHello();
}
}
spring-dao.xml —— 定義 DAO Bean,採用單例且立即初始化:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloDaoImpl" class="www.csdn.spring.dao.HelloDaoImpl"
scope="singleton" lazy-init="default"></bean>
</beans>
spring-service.xml —— 定義 Service Bean,通過 <property> 注入 DAO:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://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="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />
</beans>
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.service.HelloService;
public class DemoTest {
@Test
public void test() {
// 手動創建對比(非 Spring 管理)
HelloDao helloDao = new HelloDaoImpl();
helloDao.sayHello();
// Spring 容器管理模式(註釋部分為演示代碼)
/*
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
HelloDao dao = context.getBean("helloDaoImpl", HelloDao.class);
dao.sayHello();
HelloService service = context.getBean("helloServiceImpl", HelloService.class);
service.sayHello();
*/
}
}
HelloDaoImpl 實例化.......
say:hello
控制台輸出證明:
lazy-init="default" 等同於 false)<import> 實現配置模塊化