IOC 三层架构 代码
步骤:
1.导入spring坐标
2.写业务层与表现层接口与实现类
3.写spring配置文件
4.配置所需资源service为spring的控制资源
5.表现层App通过spring获取资源
在pom文件中 导入spring坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
service层接口
public interface UserService {
public void save();
}
service层接口的实现类
public class UserServiceImpl implements UserService {
public void save() {
System.out.println("洛天依,米库");
}
}
写spring配置文件 在spring官网spring.io里找
Spring Framework 的 Learn 第一个文档
选择core核心容器
复制这个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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
这就是spring配置文件的结构头
将它写到 src目录下main—>resources里
spring配置文件的标准名称
applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建spring控制的资源-->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
</beans>
bean spring的配置在bean标签中进行
id=“userService” 写的是service层的接口名
class="com.itheima.service.impl.UserServiceImpl"写的是service层的接口实现类的全类名
在这方法中读取spring配置文件, 调用service层save方法
public class UserApp {
public static void main(String[] args) {
// 加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取资源
UserService userService = (UserService)ctx.getBean("userService");
//调用userService接口的save
userService.save();
}
}
new ClassPathXmlApplicationContext(“applicationContext.xml”);
用它读取 spring配置文件 得到ApplicationContext对象
(UserService)ctx.getBean(“userService”);通过getBean(“userService”)方法,参数是 spring配置文件中bean标签的id值,这样得到的是Object类型对象,所以再将它强转成UserService接口对象,就能得到userService对象,
再spring配置文件
applicationContext.xml
用
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
配置好了 userService接口 与UserServiceImpl实现类
的对应关系,这样就是
userService接口 = UserServiceImpl实现类
因此可以用
userService接口 调用UserServiceImpl实现类 save();方法
在这里配置文件头复制后,报红是因为maven没有识别到这个配置文件头的uri路径,
1,检查spring坐标有没有写在pom文件里
2,尝试刷新一遍
3,在maven project 选中这个项目右键 选择 remove移除,在点击上面的加号,找到这个项目的pom文件重新导入
出现这种情况,8成是买到劣质电脑,或者是硬件老化。