Spring IOC/DI

本文深入解读Spring框架中的IoC(Dependency Injection)与DI(控制反转)概念,阐述如何通过Spring容器实现对象的创建与管理。同时,介绍面向切面编程(AOP)在Spring中的应用,包括切面、切入点与通知的定义与实现。通过实例展示了如何配置和使用Spring的ApplicationContext容器,以及Bean的装配与实例化过程。最后,探讨了依赖注入的多种方式,并提供具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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”/>

依赖注入几种方式

转载于:https://www.cnblogs.com/Irving/p/3308419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值