特别说明: spring5版本是用jdk8编写的,所以要求我们的jdk版本是8及以上。 同时tomcat的版本要求8.5及以上。
一、导入maven依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
二、创建相应的接口和实现类
文件目录如下,后面给出相应的代码
- AccountDaoImpl
package com.dgut.dao.impl;
import com.dgut.dao.IAccountDao;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
public void saveAccount(){
System.out.println("保存了账户");
}
}
- IAccountDao
package com.dgut.dao;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 模拟保存账户
*/
void saveAccount();
}
- IAccountServiceImpl
package com.dgut.service.impl;
import com.dgut.dao.IAccountDao;
import com.dgut.dao.impl.AccountDaoImpl;
import com.dgut.service.IAccountService;
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}
- IAccountService
package com.dgut.service;
/**
* 账户业务层的接口
*/
public interface IAccountService {
/**
* 模拟保存账户
*/
void saveAccount();
}
- Client
package com.dgut.ui;
import com.dgut.dao.IAccountDao;
import com.dgut.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {
/**
* 获取ioc核心容器,并根据id获取对象
* @param args
*/
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
IAccountService accountService = (IAccountService)ac.getBean("accountService");
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(accountDao);
System.out.println(accountService);
}
}
- beam.xml
<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 id="accountService" class="com.dgut.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.dgut.dao.impl.AccountDaoImpl"></bean>
</beans>
三、测试
在Client中运行main方法进行测试