初识Spring-ioc

简介: 初识Spring-ioc

1. Spring的简介

Spring是一个开源的Java开发框架,用于构建企业级应用程序。它提供了一种轻量级的、非侵入式的编程模型,使得开发者可以更加简单地构建可扩展、可维护的应用程序。

Spring框架的核心特性包括依赖注入(Dependency Injection)和面向切面编程(Aspect-Oriented

Programming)。依赖注入使得开发者可以将对象之间的依赖关系交由框架来管理,从而降低了组件之间的耦合度。面向切面编程则提供了一种在应用程序中横切关注点的方式,例如日志记录、事务管理等。

Spring框架还提供了许多其他功能和模块,如Spring MVC用于构建Web应用程序、Spring

Data用于简化数据库访问、Spring

Security用于身份验证和授权等。这些模块可以根据需要进行选择和集成,使得开发者可以根据自己的需求来构建定制化的应用程序。

总的来说,Spring框架通过提供一种简单、灵活的开发方式,帮助开发者构建高效、可扩展的Java应用程序。它已经成为Java开发领域中最受欢迎的框架之一,并被广泛应用于各种企业级应用程序的开发中。

2.Spring容器ioc的特点

Spring的IOC(Inversion of Control)容器是Spring框架的核心组件之一,它具有以下特点:

依赖注入(Dependency Injection)

:IOC容器通过依赖注入的方式管理对象之间的依赖关系。开发者只需要定义好对象之间的依赖关系,IOC容器会负责实例化对象并自动注入所需的依赖,从而降低了组件之间的耦合度。

配置灵活性:IOC容器使用外部配置文件(如XML、注解或Java配置类)来描述对象的创建和依赖关系,这使得应用程序的配置更加灵活。开发者可以根据需要修改配置文件,而无需修改源代码,从而实现应用程序的灵活性和可维护性。

单例管理:IOC容器默认情况下管理的对象是单例的,即每个对象在容器中只有一个实例。这样可以节省资源并提高性能。开发者也可以通过配置来改变对象的作用域,如原型(每次请求都创建新的实例)或会话(每个会话创建一个实例)。

生命周期管理:IOC容器负责管理对象的生命周期,包括对象的创建、初始化和销毁。开发者可以通过配置回调方法(如初始化方法和销毁方法)来实现对对象生命周期的控制。

AOP集成:IOC容器与面向切面编程(AOP)紧密集成,可以通过配置将横切关注点(如日志、事务管理)应用到应用程序中的多个对象上,从而提高代码的重用性和可维护性。

总的来说,Spring的IOC容器通过依赖注入、灵活的配置、单例管理、生命周期管理和AOP集成等特点,提供了一种简单、灵活、可扩展的对象管理机制,帮助开发者构建可维护、可测试的应用程序。

3.spring注入方式

Spring框架提供了多种方式来实现依赖注入(Dependency Injection): 构造函数注入(Constructor

Injection):通过构造函数来注入依赖。在类的构造函数中声明依赖的参数,Spring容器会根据配置自动实例化并注入所需的依赖。

1.Setter方法注入(Setter Injection):通过Setter方法来注入依赖。在类中定义对应的Setter方法,并在方法中接收依赖的参数,Spring容器会通过调用Setter方法来注入所需的依赖。

模拟:

package com.niyin.ioc.web;
import com.niyin.ioc.impl.UserServiceImpl;
import com.niyin.ioc.impl.UserServiceImpl1;
import com.niyin.ioc.service.UserService;
import java.util.List;
public class GoodsAction {
    private UserService userService;
 private String gname;
 private  int age;
 private List<String>peoples;
    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public List<String> getPeoples() {
        return peoples;
    }
    public void setPeoples(List<String> peoples) {
        this.peoples = peoples;
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    public String update(){
        userService.update();
        return "list";
    }
public void pros(){
    System.out.println(this.gname);
    System.out.println(this.age);
    System.out.println(this.peoples);
};
}
package com.niyin.ioc.demo;
import com.niyin.ioc.web.GoodsAction;
import com.niyin.ioc.web.UserAction;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("/sping-context.xml");
        UserAction userAction= (UserAction) context.getBean("userAction");
        userAction.update();
        GoodsAction goodsAction= (GoodsAction) context.getBean("goodsAction");
        goodsAction.update();
        System.out.println("--------------------------------");
        goodsAction.pros();
        System.out.println("---------------------------------");
        userAction.pros();
    }
}
<bean class="com.niyin.ioc.web.GoodsAction" id="goodsAction">
        <property name="userService" ref="userService"></property>
    <property name="gname" value="雨伞"></property>
        <property name="age" value="1"></property>
        <property name="peoples" >
            <list>
                <value>男的</value>
                <value>女的</value>
            </list>
        </property>
    </bean>

2.构造函数注入

package com.niyin.ioc.web;
import com.niyin.ioc.impl.UserServiceImpl;
import com.niyin.ioc.service.UserService;
import java.util.List;
public class UserAction {
    private UserService userService;
    private String uname;
    private int age;
    private List<String>hobby;
    public UserAction() {
    }
    public UserAction(String uname, int age, List<String> hobby) {
        this.uname = uname;
        this.age = age;
        this.hobby = hobby;
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    public String update(){
        userService.update();
        return "list";
    }
    public void pros(){
        System.out.println(this.uname);
        System.out.println(this.age);
        System.out.println(this.hobby);
    };
}
package com.niyin.ioc.demo;
import com.niyin.ioc.web.GoodsAction;
import com.niyin.ioc.web.UserAction;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("/sping-context.xml");
        UserAction userAction= (UserAction) context.getBean("userAction");
        userAction.update();
        GoodsAction goodsAction= (GoodsAction) context.getBean("goodsAction");
        goodsAction.update();
        System.out.println("--------------------------------");
        goodsAction.pros();
        System.out.println("---------------------------------");
        userAction.pros();
    }
}
<bean class="com.niyin.ioc.web.UserAction" id="userAction">
    <property name="userService" ref="userService"></property>
<constructor-arg name="uname" value="袁辉sb"></constructor-arg>
    <constructor-arg name="age" value="11"></constructor-arg>
    <constructor-arg name="hobby" >
        <list>
            <value>
                农村
            </value>
            <value>
                农村
            </value>
            <value>
                农村
            </value>
        </list>
    </constructor-arg>
</bean>

3.在Spring IOC(控制反转)中,"byname"和"bytype"是两种不同的依赖注入方式。

ByName(按名称):当使用ByName方式进行依赖注入时,Spring容器会根据依赖对象的名称来进行匹配和注入。在配置文件中,需要使用元素的name属性来指定依赖对象的名称。Spring容器会在容器中查找与指定名称匹配的bean,并将其注入到相应的属性中。

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等)进行集成,通过配置文件或注解来实现。

配置监听器

1.监听器

package com.niyin.ioc.listerner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class SpingLoadListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("/sping-context.xml");
ServletContext servletContext= sce.getServletContext();
servletContext.setAttribute("springContext",context);
    }
}

2.servlet

package com.niyin.ioc.web;
import com.niyin.ioc.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;
@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 {
        ClassPathXmlApplicationContext context= (ClassPathXmlApplicationContext) req.getServletContext().getAttribute("spingContext");
         UserService userService= (UserService) context.getBean("userService");
        System.out.println(userService);
        userService.update();
    }
}

4.总结

本文深入探讨了Spring IOC容器的工作原理,包括配置文件、Bean的定义、实例化、装配、生命周期管理和获取等方面。通过理解和应用Spring IOC容器,我们可以更好地开发和管理Java应用程序,提高代码的可维护性和可测试性。希望本文对读者有所帮助,谢谢阅读!

目录
相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8049 2
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18049 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
2天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
765 0
|
8天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1459 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2566 8
|
20天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
4057 22