Loading

spring入门案例

案例环境说明

  • 模拟三层架构中表现层调用业务层功能

    • 表现层:UserApp模拟UserServlet(使用main方法模拟)

    • 业务层:UserService

IoC入门案例制作步骤

1.导入spring坐标(5.1.9.release)

2.编写业务层与表现层(模拟)接口与实现类

3.建立spring配置文件

4.配置所需资源(Service)为spring控制的资源

5.表现层(App)通过spring获取资源(Service实例)

 

导入spring坐标:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>

编写表现层、业务层接口和实现类:

业务层接口:

public interface UserService {
    //业务方法  
    void save();
}

业务层实现类:

public class UserServiceImpl implements UserService {
    public void save() {
        System.out.println("user service running...");
    }
}

创建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">
    <!-- 1.创建spring控制的资源-->
    <bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
</beans>

模拟表现层加载获取spring资源:

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();
    }
}

 

posted @ 2022-03-26 16:04  1640808365  阅读(108)  评论(0编辑  收藏  举报