Spring 6.0官方文档示例(22): singleton类型的bean和prototype类型的bean协同工作的方法(一)

一、配置文件:


	
	

	
	
	

二、实体类

package cn.edu.tju.domain;

import java.time.LocalDateTime;
import java.util.Map;

public class Command {
	private Map state;

	public Map getState() {
		return state;
	}

	public void setState(Map state) {
		this.state = state;
	}

	public Object execute(){
		System.out.println(LocalDateTime.now().toLocalTime());
		return null;
	}


}

package cn.edu.tju.domain;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

public class CommandManager implements ApplicationContextAware {
	private ApplicationContext applicationContext;
	public Object process(Map commandState) {
		// grab a new instance of the appropriate Command
		Command command = createCommand();
		// set the state on the (hopefully brand new) Command instance
		command.setState(commandState);
		return command.execute();
	}
	protected Command createCommand() {
		// notice the Spring API dependency!
		return this.applicationContext.getBean("command", Command.class);
	}
	public void setApplicationContext(
			ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}

三、主类:

package cn.edu.tju;

import cn.edu.tju.domain.CommandManager;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;

public class TestDiffScope {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test7.xml","test2.xml");
		CommandManager commandManager = context.getBean("commandManager", CommandManager.class);
		commandManager.process(new HashMap());
		CommandManager commandManager2 = context.getBean("commandManager", CommandManager.class);
		commandManager2.process(new HashMap<>());
	}
}

你可能感兴趣的:(Spring,spring,单例模式,原型模式)