整体架构
在IDEA中创建maven项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.uek</groupId>
<artifactId>spring01-study01-spring-ioc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.12.RELEASE</version>
</dependency>
</dependencies>
</project>
dao层
public interface IAccountDao {
void saveAccount();
}
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
service层
public interface IAccountService {
//保存账户
void saveAccount();
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
表现层
public class Client {
//获取Spring的IOC核心容器,并根据id获取对象
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
IAccountService ias = (IAccountService) ac.getBean("accountService");
IAccountDao iad = ac.getBean("accountDao", IAccountDao.class);
System.out.println(ias);
System.out.println(iad);
}
}
bean.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 id="accountService" class="com.uek.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.uek.dao.impl.AccountDaoImpl"></bean>
</beans>