在将要被加入到spring容器中的service中,添加static静态代码块(加载类时被调用),用于判断spring中新旧bean工厂的加载性质。
package com.witwicky.service.impl;
import com.witwicky.service.UserService;
public class UserServiceImpl implements UserService {
static{
System.out.println("init...");
}
@Override
public void hello() {
System.out.println("hello");
}
}
package spring;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import com.witwicky.service.UserService;
import com.witwicky.service.impl.UserServiceImpl;
public class Demo1 {
@Test
public void run1() {
UserService us = new UserServiceImpl();
us.hello();
}
/**
* 新工厂,当spring核心配置文件被加载完成时,其中配置的bean就已经被实例化
*/
@Test
public void run2() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// UserService us = (UserService) ctx.getBean("userService");
// us.hello();
}
/**
* 旧工厂,延迟加载,只有在获取bean工厂里的对象时,才会被实例化。
*/
@Test
public void run3() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
// UserService us = (UserService) bf.getBean("userService");
// us.hello();
}
}
当run2执行时(注释掉后两行代码),控制台会打印初始化信息。
当run3执行时(注释掉后两行代码),控制台并不会打印初始化信息,而将后两行代码开启时,则初始化信息与打印信息一同输出。