Spring IOC

来源:互联网 发布:java无法访问的语句 编辑:程序博客网 时间:2024/06/01 23:36

Spring的核心理念是IOC(控制反转)和AOP(面向切面),IOC是基础,aop是重要的功能,运用aop的典型是数据库事物的运用。

1.被动创建对象(不是自己创建的,是别人帮你创建的(IOC)

1.1代码实现

package com.hanrun;
public class Juice {
private String beverageshop=null;
private Source source=null;
public String makeJuice(){
String juice="这是一杯由"+beverageshop+"饮品店,提供的"+source.getSize()+source.getFruit();
return juice;
}
}

package com.hanrun;
class Source{
private String size;
private String fruit;
}

1.2xml配置

<bean id="source" class="com.hanrun.Source">
<property name="size" value="中" />
<property name="fruit" value="加糖" />
</bean>


<bean id="juice" class="com.hanrun.Juice">
<property name="beverageshop" value="贡茶" />
<property name="source" hrf="source" />
</bean>

这样一个对象就由xml配置好了

Spring ioc容器设计主要基于BeanFactory和ApplicationContext两个接口ApplicationContext(封装很多方法,很多时候就用他)是BeanFactory(最底层接口)的子接口

ApplicationContext tex=new ClassPathXmlApplicationContext("xml文件.xml");
Juice j=(Juice) tex.getBean("juice");

以上是创建bean的过程

依赖注入:注入配置资源给Bean,这样才算创建完成。spring有一个配置lazy-init,默认false表示非懒加载(一开始就注入生成bean),如果设置为true时是懒加载。


原创粉丝点击