“深入了解Spring框架:IOC、注入方式和与Web容器的整合“

简介: “深入了解Spring框架:IOC、注入方式和与Web容器的整合“

Spring是一个轻量级的开源Java框架,用于构建企业级应用程序。它提供了一种全面的编程和配置模型,用于开发灵活、可扩展的应用程序。Spring框架的核心特性包括依赖注入(DI)、面向切面编程(AOP)、控制反转(IOC)等。

2. Spring的IOC(控制反转)

IOC是Spring框架的核心概念之一,也是Spring框架的基石。IOC的基本思想是将对象的创建、组装和管理交给Spring容器来完成,而不是由开发人员手动管理对象的生命周期。通过IOC,开发人员可以将应用程序的各个组件解耦,提高代码的可维护性和可测试性。

  • spring-context.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">
    <bean class="com.yuan.web.UserAction" id="userAction" >
        <property name="userService" ref="userService"></property>
    </bean>
    <bean class="com.yuan.web.GoodsAction" id="goodsAction" >
        <property name="userService" ref="userService2"></property>
    </bean>
    <bean class="com.yuan.service.impl.UserServiceimpl1" id="userService"></bean>
    <bean class="com.yuan.service.impl.UserServiceimpl2" id="userService2"></bean>
</beans>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
  • UserService
package com.yuan.service;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 14:10
 */
public interface UserService {
    public void update();
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
  • UserAction
package com.yuan.web;
import com.yuan.service.UserService;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 14:15
 */
public class UserAction {
    private UserService userService;
    public String update(){
        userService.update();
        return "list";
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
  • GoodsAction
package com.yuan.web;
import com.yuan.service.UserService;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 14:15
 */
public class UserAction {
    private UserService userService;
    public String update(){
        userService.update();
        return "list";
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
  • 测试类
package com.yuan.text;
import com.yuan.web.GoodsAction;
import com.yuan.web.UserAction;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 14:27
 */
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
        UserAction userAction = (UserAction) context.getBean("userAction");
             userAction.update();
        GoodsAction goodsAction = (GoodsAction) context.getBean("goodsAction");
            goodsAction.update();
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
  • 运行结果

3. Spring的注入方式

Spring框架提供了多种注入方式,以满足不同场景下的需求。下面介绍三种常用的注入方式:

3.1 第一种:构造函数注入

构造函数注入是通过调用目标对象的构造函数来完成依赖注入。在Spring配置文件中,通过标签指定构造函数的参数值或引用。

  • spring-context.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">
    <bean class="com.yuan.web.UserAction" id="userAction" >
        <property name="userService" ref="userService"></property>
        <constructor-arg name="uname" value="狗"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="pros">
            <list>
                <value>维多利亚狗</value>
                <value>土狗</value>
            </list>
        </constructor-arg>
    </bean>
    <bean class="com.yuan.web.GoodsAction" id="goodsAction" >
        <property name="userService" ref="userService2"></property>
        <property name="gname" value="电脑"></property>
        <property name="age" value="10"></property>
        <property name="pors">
            <list>
                <value>程序员</value>
                <value>社会人</value>
            </list>
        </property>
    </bean>
    <bean class="com.yuan.service.impl.UserServiceimpl1" id="userService"></bean>
    <bean class="com.yuan.service.impl.UserServiceimpl2" id="userService2"></bean>
</beans>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
  • 运行结果

3.2 第二种:Setter方法注入

Setter方法注入是通过调用目标对象的Setter方法来完成依赖注入。在Spring配置文件中,通过标签指定属性的值或引用。

  • spring-context.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">
    <bean class="com.yuan.web.UserAction" id="userAction" >
        <property name="userService" ref="userService"></property>
    </bean>
    <bean class="com.yuan.web.GoodsAction" id="goodsAction" >
        <property name="userService" ref="userService2"></property>
        <property name="gname" value="电脑"></property>
        <property name="age" value="10"></property>
        <property name="pors">
            <list>
                <value>程序员</value>
                <value>社会人</value>
            </list>
        </property>
    </bean>
    <bean class="com.yuan.service.impl.UserServiceimpl1" id="userService"></bean>
    <bean class="com.yuan.service.impl.UserServiceimpl2" id="userService2"></bean>
</beans>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
  • 运行结果

3.3 第三种:注解注入

注解注入是通过在目标对象的属性、构造函数或Setter方法上添加注解来完成依赖注入。常用的注解包括@Autowired、@Resource等。

按名称注入(byname):

使用@Autowired注解时,如果存在多个同类型的Bean对象,Spring会根据依赖对象的名称来进行注入。

在注入时,Spring会查找与依赖对象名称相同的Bean对象,并将其注入到目标对象中。

如果找不到与依赖对象名称相同的Bean对象,Spring会抛出异常。

按类型注入(byType):

使用@Autowired注解时,如果存在多个同类型的Bean对象,Spring会根据依赖对象的类型来进行注入。

在注入时,Spring会查找与依赖对象类型相同的Bean对象,并将其注入到目标对象中。

如果找不到与依赖对象类型相同的Bean对象,Spring会抛出异常。

4. Spring与Web容器的整合

Spring框架与Web容器的整合是为了更好地支持Web应用程序的开发。Spring提供了多种方式与Web容器进行整合,常见的方式包括:

  • 4.1 使用Spring MVC框架:Spring MVC是Spring框架的一部分,用于开发基于MVC模式的Web应用程序。通过配置Spring MVC,可以将请求映射到相应的控制器,并实现灵活的请求处理和视图渲染。
  • 4.2 使用Spring Boot:Spring Boot是Spring框架的扩展,用于简化Spring应用程序的开发和部署。Spring Boot提供了内嵌的Web容器,可以直接运行Spring应用程序,无需额外配置。
  • 4.3 使用Spring和其他Web容器的集成:Spring框架可以与其他常见的Web容器(如Tomcat、Jetty等)进行集成,通过配置文件或注解来实现。

配置监听器

package com.yuan.listeer;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 16:40
 */
@WebListener("")
public class SpringLoadListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        //将spring上下文放入Tomcat上下文
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
        //获取Tomcat上下文
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute("springContext",context);
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31

配置Servlet

package com.yuan.servlet;
import com.yuan.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 16:49
 */@WebServlet("/userList")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取spring上下文对象
        ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) req.getServletContext().getAttribute("springContext");
        UserService userService = (UserService) context.getBean("userService");
        userService.update();
        System.out.println(userService);
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
• 32
• 33
• 34
• 35
  • 运行结果

总结:

本篇博客介绍了Spring框架的基本概念和核心特性,重点讲解了IOC、注入方式和与Web容器的整合。通过深入了解Spring框架,开发人员可以更好地利用Spring提供的功能和特性,提高应用程序的开发效率和质量。


相关文章
|
7月前
|
缓存 安全 Java
《深入理解Spring》过滤器(Filter)——Web请求的第一道防线
Servlet过滤器是Java Web核心组件,可在请求进入容器时进行预处理与响应后处理,适用于日志、认证、安全、跨域等全局性功能,具有比Spring拦截器更早的执行时机和更广的覆盖范围。
|
7月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
7月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
732 2
|
9月前
|
运维 数据可视化 C++
2025 热门的 Web 化容器部署工具对比:Portainer VS Websoft9
2025年热门Web化容器部署工具对比:Portainer与Websoft9。Portainer以轻量可视化管理见长,适合技术团队运维;Websoft9则提供一站式应用部署与容器管理,内置丰富开源模板,降低中小企业部署门槛。两者各有优势,助力企业提升容器化效率。
597 1
2025 热门的 Web 化容器部署工具对比:Portainer VS Websoft9
|
8月前
|
存储 安全 Java
如何在 Spring Web 应用程序中使用 @SessionScope 和 @RequestScope
Spring框架中的`@SessionScope`和`@RequestScope`注解用于管理Web应用中的状态。`@SessionScope`绑定HTTP会话生命周期,适用于用户特定数据,如购物车;`@RequestScope`限定于单个请求,适合无状态、线程安全的操作,如日志记录。合理选择作用域能提升应用性能与可维护性。
367 1
|
9月前
|
存储 NoSQL Java
探索Spring Boot的函数式Web应用开发
通过这种方式,开发者能以声明式和函数式的编程习惯,构建高效、易测试、并发友好的Web应用,同时也能以较小的学习曲线迅速上手,因为这些概念与Spring Framework其他部分保持一致性。在设计和编码过程中,保持代码的简洁性和高内聚性,有助于维持项目的可管理性,也便于其他开发者阅读和理解。
258 0
|
10月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
740 0
|
XML Java 数据格式
Spring IoC容器的设计与实现
Spring 是一个功能强大且模块化的 Java 开发框架,其核心架构围绕 IoC 容器、AOP、数据访问与集成、Web 层支持等展开。其中,`BeanFactory` 和 `ApplicationContext` 是 Spring 容器的核心组件,分别定位为基础容器和高级容器,前者提供轻量级的 Bean 管理,后者扩展了事件发布、国际化等功能。
346 18
|
XML Java 数据格式
京东一面:spring ioc容器本质是什么? ioc容器启动的步骤有哪些?
京东一面:spring ioc容器本质是什么? ioc容器启动的步骤有哪些?
|
XML Java 数据格式
Spring容器的本质
本文主要讨论Spring容器最核心的机制,用最少的代码讲清楚Spring容器的本质。