spring extral features-----StaticApplicationContext

@Test
	public void test(){
		//通过编程的方式去启动一个bean容器---该类通常用于测试,用于加载任意的外部资源,而不用加载特定格式的文件
		StaticApplicationContext  staticAppContext=new StaticApplicationContext();
		
		MutablePropertyValues pvs=new MutablePropertyValues();
		//在创建对象,需要指定实现类,不能是用抽象类或者接口,否则会出现错误
		staticAppContext.registerSingleton("userDao", UserDaoImpl.class);

		//创建为UserServiceImpl---可以通过
		pvs.add("userDao", staticAppContext.getBean(UserDao.class));
		//注册为单例模式 		并将属性键值对传入,value可以为引用类型
		staticAppContext.registerSingleton("userService", UserServiceImpl.class, pvs);
		
		staticAppContext.registerSingleton("userService2", UserServiceImpl2.class);
		
		
		UserService userService=staticAppContext.getBean("userService",UserService.class);
		userService.save("hot", "123456");
		
		ConfigurableListableBeanFactory factory=staticAppContext.getBeanFactory();
		
		Map<String, Object> beans=factory.getBeansWithAnnotation(Quality.class);
		Iterator<Object> iterator=beans.values().iterator();
		
		while(iterator.hasNext()){
			System.err.println(iterator.next().getClass());
		}
		
		staticAppContext.close();
		
		
	}

    我们可以通过上述的机制,来完成特殊的应用需求。例如,在web app启动的时候,从远程加载bean定义文件;动态创建bean;当然也可以通过别的机制完成特殊需求。各位根据自己的业务可以进行特殊定义

猜你喜欢

转载自hotbain.iteye.com/blog/1896715