版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxdeng/article/details/82904338
1. 创建Maven工程,并引入JAR
JAR 包引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
创建Spring核心配置文件
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">
</beans>
创建类
DAO 层
package com.javaee.spring.dao;
public class ExampleDao {
public void save() {
System.out.println("------ dao save() ------");
}
}
Service 层
package com.javaee.spring.service;
import com.javaee.spring.dao.ExampleDao;
public class ExampleService{
private ExampleDao exampleDao;
public void save() {
System.out.println("------ service save() ------");
exampleDao.save();
}
public void setExampleDao(ExampleDao exampleDao) {
this.exampleDao = exampleDao;
}
}
注册Bean
<bean id="exampleService" class="com.javaee.spring.service.ExampleService">
<property name="exampleDao" ref="exampleDao" />
</bean>
<bean id="exampleDao" class="com.javaee.spring.dao.ExampleDao"></bean>
测试
public class ExampleBeanTest {
private ClassPathXmlApplicationContext context;
private ExampleService exampleService;
@Before
public void init() {
context = new ClassPathXmlApplicationContext("spring.xml");
exampleService = (ExampleService) context.getBean("exampleService");
}
@Test
public void save() {
exampleService.save();
}
}