DEBUG 2015-01-14 11:13:05,622 org.springframework.beans.factory.support.AbstractBeanFactory: Returning cached instance of singleton bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@152bdc7
DEBUG 2015-01-14 11:13:05,622 org.springframework.beans.factory.support.AbstractBeanFactory: Returning cached instance of singleton bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@152bdc7
DEBUG 2015-01-14 11:13:05,622 org.springframework.beans.factory.support.AbstractBeanFactory: Returning cached instance of singleton bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@152bdc7
结论:service对象在单例情况下只有1个。
当参数为多例时:
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class OrderService {
public void sayMyName() {
System.out.println("MyName: " + this);
}
}
public static void main(String[] args) {
SpringUtils.getSpringContext();
SpringUtils.getBeansByClassType(OrderService.class).sayMyName();
SpringUtils.getBeansByClassType(OrderService.class).sayMyName();
SpringUtils.getBeansByClassType(OrderService.class).sayMyName();
}
DEBUG 2015-01-14 11:15:30,648 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory: Finished creating instance of bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@cab854
DEBUG 2015-01-14 11:15:30,648 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory: Creating instance of bean ‘orderService’
DEBUG 2015-01-14 11:15:30,648 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory: Finished creating instance of bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@10bbd42
DEBUG 2015-01-14 11:15:30,648 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory: Creating instance of bean ‘orderService’
DEBUG 2015-01-14 11:15:30,648 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory: Finished creating instance of bean ‘orderService’
MyName: com.honzh.socket.server.business.test.OrderService@1b6772a
结论:prototype状态下,service在获取时会重新加载一个新的对象。
附上SpringUtils类,该类是为了通过applicationContext文件,加载对应的spring组件。
private static ApplicationContext factory;
private SpringUtils() {
};
public synchronized static ApplicationContext getSpringContext() throws BeansException {
if (factory == null) {
factory = new ClassPathXmlApplicationContext(“/com/honzh/socket/server/business/applicationContext.xml”);
}
return factory;
}
public synchronized static ApplicationContext getSpringContext(String appContextPath) throws BeansException {
if (factory == null) {
factory = new ClassPathXmlApplicationContext(appContextPath);
}
return factory;
}
public static T getBeansByClassType(Class requiredType) {
return factory.getBean(requiredType);
}
TransactionConfiguration