spring中的ioc解决程序的耦合入门
1、导入环境
maven导入
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.x.x</version>
</dependency>
</dependencies>
开发包下载地址: http://repo.springsource.org/libs-release-local/org/springframework/spring 需要注意的是spring5版本是基于jdk8编写的所以使用spring5,jdk的版本必须是jdk8以上的版本。
2、接口及其实现类的创建
实例项目结构 dao层
public interface AccountDao {
void save();
}
public class AccountDaoImpl implements AccountDao {
@Override
public void save() {
System.out.println("账户已保存!!!");
}
}
service层
public interface AccountService {
void save();
}
public class AccountServiceImpl implements AccountService {
@Override
public void save() {
}
}
ui层
public class Client {
public static void main(String[] args) {
//1.获取核心容器对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//2. 获取对象
AccountDaoImpl accountDao = context.getBean("accountDao", AccountDaoImpl.class);
AccountServiceImpl accountService = context.getBean("accountService", AccountServiceImpl.class);
System.out.println(accountDao);
System.out.println(accountService);
}
}
容器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.yzx.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.yzx.dao.impl.AccountDaoImpl"></bean>
</beans>
3、运行测试
运行Client类的main方法,发现对象已被创建。
