SYSTEM
入门项目
src/content/notes/system/入门项目.md 入门项目
模拟三层架构中表现层调用业务层功能
-
表现层:UserApp 模拟 UserServlet(使用 main 方法模拟)
-
业务层:UserService
步骤:
-
导入 spring 坐标(5.1.9.release)
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> -
编写业务层与表现层(模拟)接口与实现类 service.UserService,service.impl.UserServiceImpl
public interface UserService { //业务方法 void save(); }public class UserServiceImpl implements UserService { public void save() { System.out.println("user service running..."); } } -
建立 Spring 配置文件:resources.applicationContext.xml (名字一般使用该格式)
-
配置所需资源(Service)为 Spring 控制的资源
<?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"> <!-- 1.创建spring控制的资源--> <bean id="userService" class="service.impl.UserServiceImpl"/> </beans> -
表现层(App)通过 Spring 获取资源(Service 实例)
public class UserApp { public static void main(String[] args) { //2.加载配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //3.获取资源 UserService userService = (UserService) ctx.getBean("userService"); userService.save();//user service running... } }