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


在这里插入图片描述

1. Spring框架简介

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>
  • UserService
package com.yuan.service;

/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-15 14:10
 */
public interface UserService {
    public void update();
}

  • 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;
    }
}

  • 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;
    }
}

  • 测试类
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();
    }
}

  • 运行结果
    在这里插入图片描述

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>
  • 运行结果
    在这里插入图片描述

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>
  • 运行结果
    在这里插入图片描述

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


    }

}

配置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);

    }
}

  • 运行结果
    在这里插入图片描述

总结:

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

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值