Spring IOC/DI
Spring核心 IoC/DI
IoC/DI:Inversion of Control,控制反转 ,Dependency Injection 依赖注入
传统的java开发模式中,当我们需要一个对象时,我们自己创建一个对象出来,而在Spring中,一切都有Spring容器使用了工厂模式为我们创建管理需要的对象。
AOP:Aspect Oriented Programming 面向切面
AOP是Aspect Oriented Programming的缩写,意思是面向方面编程,而在面向切面编程中,我们将一个对象某些类似的方面横向抽象成一个切面,对这个切面进行一些如权限验证,事物管理,记录日志等操作。
Bean装配与实例化
BeanFactory和ApplicationContext就是spring框架的两个IOC容器,现在一般使用ApplicationnContext,其不但包含了BeanFactory的作用,同时还进行更多的扩展。(官网文档解释)。
The org.springframework.beans
and org.springframework.context
packages are the basis for Spring Framework's IoC container. The BeanFactory
interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext
is a sub-interface of BeanFactory.
It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext
for use in web applications.
public interface IUserService { public void sayName(); } public class UserServiceImpl implements IUserService { @Override public void sayName() { System.out.println("My name is Spring IOC"); } } ApplicationContext contextClassPath = new ClassPathXmlApplicationContext("applicationContext.xml"); //ApplicationContext contextFileSystem = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml"); UserServiceImpl userImpl = (UserServiceImpl) contextClassPath.getBean(UserServiceImpl.class); userImpl.sayName();
实例化Spring IOC容器的简单方法(JDK5+ 支持泛型)
1.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring配置文件路径"});
2.(已废弃)
Resource res = new FileSystemResource("spring配置文件");
BeanFactory factory = new XMLBeanFactory(res);
3.ApplicationContext contextFileSystem = new FileSystemXmlApplicationContext(new String[]{"spring配置文件路径"});
Bean的XML配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="userservice" class="cn.base.web.service.impl.UserServiceImpl"></bean> </beans>
1.一个Bean对应一个id,如果spring配置文件中有两个以上相同的id时,spring会报错。
2.一个Bean也可以通过一个name属性来引用和指定,如果spring配置文件中有两个以上相同name的Bean,则spring通过name引用时会自动覆盖前面相同name的bean引用。
很多时候,由于Spring需要管理和配置的东西比较多,我们可以根据模块分解开,过<import>元素将要引入的spring其他配置文件,如
<import resource=”spring-service.xml”/>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述