首页 > 编程知识 正文

spring ioc和aop原理,spring ioc原理

时间:2023-05-04 14:24:33 阅读:160439 作者:4393

spring ioc原理分析http://www.Sina.com/http://www.Sina.com/http://www.Sina.com/spring IOC的概念ioc:通过spring管理对象的创建例如,我们以前使用名为new的对象方法自己创建对象,但现在使用spring,不需要自己new对象,而是使用其他方法。

spring ioc入门applicationContext.xml

什么? XML version=' 1.0 ' encoding=' utf-8 '? beans xmlns=' http://www.spring framework.org/schema/beans ' xmlns 3360 xsi=' http://www.w3.org/2001/XML schema-instance ' xsi : schema location=' http://www.spring framework.org/schema/bean s 3358 www.spring framework spring-beans.xsd ' bean id=' hello service ' class=' demo1. hello service impl '/bean/bean

publicinterfacehelloservice { void say hello (; } HelloServiceImpl.java

publicclasshelloserviceimplimplementshelloservice { privatestring info; 公共字符串获取信息() { return info; }publicvoidsetinfo(stringinfo ) { this.info=info; } public void sayHello () system.out.println ) Hello--'info ); 使用spring创建对象

@Test //Spring开发public void demo2({ applicationcontextapplicationcontext=newclasspathxmlapplicationcontext ) ' applicationcontext ) oservicehelloservice=(hello service )应用程序上下文. get bean (hello service ); helloService.sayHello (; }要理解简单工厂法spring ioc的原理,需要知道简单工厂法

介绍简单的工厂方法

简单工厂模式是一种创建模式,用于更好地组织创建对象的代码,以适应不同情况下的对象创建和初始化。

简单的工厂方法的结构

上例中为:

HelloService是抽象产品

HelloServiceImpl是具体的产品

再写一个具体的产品吧:

HelloServiceImpl2

publicclasshelloserviceimpl2implements hello service { public void say hello (} system.out.println ) hello-hello service hello

@Test //传统方式public void demo1(() ) /程序紧密结合。 hello service hello service=newhelloserviceimpl ); helloService.sayHello (; hello服务hello服务2=newhelloserviceimpl (; helloService2.sayHello (; }我们用new方式创建对象,如何用工厂方式创建对象呢?

首先,需要创建Bean的工厂类

BeanFactory //简单工厂

public class beanfactory { publicobjectgethelloservice (string beanname ) if ) beanname.equals (hello service1 ) } { retet } } else { return null; }这样,我们以后如果想得到HelloService的话,可以做以下事情。

//客户端调用

beanfactory beanfactory=new beanfactory (; hello service hello service=(hello service ) beanfactory.get hello service (' hello service1 ' ); spirng ioc的实现原理spring ioc的实现原理实际上是单纯工厂sax分析xml反射获得类对象

在BeanFactory中,请执行以下操作:

public class beanfactory { publicobjectgetbean (string beanname )//反射分析配置文件return Class.forName )“类名”. new Instance ) }在id中,分析spring配置文件,解析为与id对应的类,得到全名,通过反射创建了类。 因此,您希望获得bean,而无需修改代码,只需添加类并在配置文件中对其进行配置即可。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。