关于Spring框架的笔记

      1.关于applicationContext.xml文件的配置,当编写好一个实体类,里面写了一些可以进行调用的方法,通过<bean>标签来将该类存储于底层,<bean id="hello" class="pojo.Hello"></bean>,其中id这个属性就是在底层Map存储中以key的形式进行保存,然后编写一个测试类,用ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");对spring容器进行定义,然后从Spring容器中用getBean("hello")获取底层Map集合中的id值,然后通过该方法来构建对象,并且进行函数方法的调用。Hello hello =  (Hello)context.getBean("hello"); hello.say();这个过程就是通过Spring来代替new Hello()去产生对象,所以是Spring的IOC过程(Inversion of Control)。但是关于底层,如果配置文件中同时出现两个<bean>标签存在相同id,那么底层Map的存储机制就会出现问题,因为一个Map中不可能出现两个相同的key,所以在Spring容器刚刚创建的时候就会报错。如果说有相同的class,而id不同,虽然在Spring容器创建的时候不会报错,但是在运用context.getBean(Hello.class);的时候,会在运行时候报错,因为计算机不知道该对哪一个class进行选择。所以在大型项目中,为了避免这种情况可以进行别名创建的方法:

<alias name="id" alias="1806班"  /> 到时候取数的时候用context.getBean("1806班");就能直接调用了。

         2.关于Spring容器进行构建对象的四种方法:(1).即以上关于创建Hello类对象,进行方法调用的实例。u(2).是关于静态工厂的创建。(3).是关于动态工厂的创建。(4).关于继承了FactoryBean接口的对象创建。

           对于静态工厂的实现,以Calendar类为例,由于Calendar类不能直接new,那么就通过Spring容器来创建实例。

<bean id="CalendarA" class="pojo.StaticFactory" factory-method="getCalendar"></bean>

public class StaticFactory{

public static Calendar getCalendar(){

  return Calendar.getInstance();

}

@Test

public void test02(){

 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Calendar calendarA = (Calendar)context.getBean("CalendarA");

System.out.println(calendarA.getTime());

}

对于动态工厂的实现,如下过程:

<bean id="newFactory" class="pojo.InstanceFactory"></bean>

<bean id="CalendarB"  factory-bean="newFactory" factory-method="getCalendar"></bean>

public class InstanceFactory(){

 public Calendar getCalendar(){

return Calendar.getInstance();

}

}

@Test
public void test03(){

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Calendar calendarB = (Calendar)context.getBean("CalendarB");

System.out.println(calendarB.getTime());

}

对于SpringFactory继承FactoryBean接口:

 <bean id="CalendarC" class="pojo.SpringFactory"></bean>

package pojo;

import java.util.Calendar;

import org.springframework.beans.factory.FactoryBean;

public class SpringFactory implements FactoryBean{

    @Override
    public Object getObject() throws Exception {
        // TODO Auto-generated method stub
        return Calendar.getInstance();
    }

    @Override
    public Class getObjectType() {
        // TODO Auto-generated method stub
        return Calendar.class;
    }

    @Override
    public boolean isSingleton() {
        // TODO Auto-generated method stub
        return false;
    }

}
 @Test
   public void test04(){
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       Calendar CalendarC = (Calendar)context.getBean("CalendarC");
       System.out.println(CalendarC.getTime());
   }

猜你喜欢

转载自blog.csdn.net/luolvzhou/article/details/82388312
今日推荐