初识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应用程序,提高代码的可维护性和可测试性。希望本文对读者有所帮助,谢谢阅读!

目录
相关文章
|
16天前
|
人工智能 自然语言处理 文字识别
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
Qwen3.7-Max是阿里云百炼面向智能体时代推出的新一代旗舰模型,对标GPT-5.5、Claude Opus 4.7等闭源旗舰。该模型支持百万级token上下文窗口,具备顶级推理能力、多模态搜索与视觉理解增强、流式输出低延迟响应等核心优势,覆盖编程、办公、长周期自主执行等复杂场景。同时支持OpenAI接口兼容,便于系统快速迁移。用户可通过Token Plan团队或节省计划等订阅方式灵活调用,适合企业级高要求场景使用。
5971 30
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
|
1天前
|
数据采集 人工智能 前端开发
让 Coding Agent 从黑盒到透明:阿里云 Agent 观测审计数据采集实践
AI Agent 规模化落地带来执行黑盒、行为难追溯、成本难度量三大难题。阿里云基于 OTel 标准,面向 Coding Agent、个人通用助理和框架型 Agent,推出 LoongSuite Pilot、插件及探针等无侵入采集方案,让 Agent 实现可看见、可分析、可审计、可治理。
569 135
|
11天前
|
存储 定位技术 数据库
CodeGraph 如何让 Claude Code减少 7 成工具调用?
CodeGraph 为 Coding Agent 提供本地代码知识图谱,把函数、类、调用链和框架路由提前整理成“项目地图”,减少盲目搜索和文件读取。它不是新 Agent,而是上下文基础设施,让 Agent 更快找到正确代码路径,平均减少 7 成工具调用。
1185 3
|
8天前
|
人工智能 安全 定位技术
CodeGraph深度解析 让Claude Code工具调用直降七成的核心原理与实操教程
如今以Claude Code为代表的AI编程智能体已经成为开发者日常编码、项目重构、漏洞修复的必备工具。但在长期使用过程中,几乎所有开发者都会遇到同一个明显痛点:AI虽然具备强大的代码生成与分析能力,却常常陷入盲目探索的循环中。
986 1
|
18天前
|
人工智能 自然语言处理 供应链
|
9天前
|
人工智能 弹性计算 安全
阿里云618活动时间、活动入口、优惠活动详细解读
2026年阿里云618创新加速季已全面开启,作为年度力度最大的云产品促销活动,本次大促覆盖轻量应用服务器、ECS云服务器、GPU云服务器、数据库、AI算力、安全服务、CDN等全品类产品,推出5亿元算力补贴、新用户限时秒杀、普惠满减、企业专享、免费试用、云大使返佣等多重福利,个人开发者、中小企业、AI团队均可享受专属低价。本文将系统梳理2026年阿里云618活动的完整时间节点、官方参与入口、各类优惠细则、使用规则、热门产品推荐及实操代码,帮助用户精准参与、高效省钱,以最低成本完成上云部署。
798 5
|
9天前
|
运维
欢迎报名|2026 Agentic AICon—智能体基础设施与AgentOps专场,邀您参会
欢迎报名|2026 Agentic AICon—智能体基础设施与AgentOps专场,邀您参会
1441 0