Spring解析

来源:互联网 发布:linux下etc没有inittab 编辑:程序博客网 时间:2024/06/16 02:13

Spring容器实现了IOC和AOP机制,这种方式大大的减少了代码之间的耦合性。

任何的java类和javaBean都可以被当成Bean处理,这些通过Spring容器管理和应用。

如何对Spring进行实例化
  1. 对系统中的配置文件进行实例化
String conf="d:applicationContext.xml";ApplicationContext ac=new FileSystemXmlApplicationContext(conf);
  1. 对工程classpath下的配置文件进行实例化
String conf="applicationContext.xml";ApplicationContext ac=new ClassPathXmlApplicationContext(conf);
如何使用Spring容器
  • 首先需要在ApplicationContext.xml中添加Bean的定义
<bean id="标识符" class="Bean类型"/>
再来说说Bean的实例化

Spring容器创建Bean对象有3中方式
1. 用构造器来实例化

<bean id="beanObject1" class="java.util.GregorianCalendar"/>

其中id或者name用于指定Bean的名称,class指定Bean的类型,会自动调用无参的构造器创建对象。
比如这个class文件的无参构造器就是这种的:

 /**     * Constructs a default <code>GregorianCalendar</code> using the current time     * in the default time zone with the default locale.     */    public GregorianCalendar() {        this(TimeZone.getDefaultRef(), Locale.getDefault());    setZoneShared(true);    }

个人理解:就是利用构造函数来创建一个对象!!!

graph LR我是构造函数-->对象
  1. 使用静态工厂方式实例化
<bean id="beanObject" class="java.util.GregorianCalendar" factory-method="getInstance"/>

id用于指定Bean的名称,class用于指定工厂的类型,factory-method用于指定工厂中创建Bean对象指定的方法,必须用static修饰的方法。

个人理解:就是利用指定类里面的一个static方法创建一个对象!!!

graph LR我是一个类中的static方法-->我是新产生的对象
  1. 使用实例工厂方式实例化
<bean id="beanObject1" class="java.util.GregorianCalendar"/><bean id="dateObject" factory-bean="beanObject1" factory-method="getTime"/>

id用于指定bean名称,factory-bean用于指定工厂bean对象,factory-method属性用于指定工厂中创建bean对象的方法。
这里定义了两个bean,其中一个bean beanObject1用于创建dateObject对象的实例工厂,第二个dateObject用于定义bean的名字,是程序代码中获得Spring管理bean对象的标识。

个人理解:就是一个bean调用了一个类中的可以创建对象的方法!

graph LR我是那个类中创建对象的方法-->我是新产生的对象
Bean指定初始化回调方法
<bean id="exampleBean" class="com.foo.ExampleBean" init-method="init"/>
指定销毁回调方法(此方法仅适用于singleton模式的bean)
<bean id="exmapleBean" class="com.foo.ExampleBean" destroy-method="destroy"/>

在ApplicationContext实现的默认行为就是在启动时将所有的singleton进行实例化,如果想延迟实例化,只需要添加属性lazy-init=”true”就可以使得bean在第一次使用时被实例化.

0 0
原创粉丝点击