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

一、配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
	">
	<bean class="cn.edu.tju.domain.CommandManager" id="commandManager"  >
	</bean>

	<bean class="cn.edu.tju.domain.Command" id="command" scope="prototype" >
	</bean>
	
</beans>

二、实体类

package cn.edu.tju.domain;

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

public class Command {
	private Map<String, Object> state;

	public Map<String, Object> getState() {
		return state;
	}

	public void setState(Map<String, Object> 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<String, Object> 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<String, Object>());
		CommandManager commandManager2 = context.getBean("commandManager", CommandManager.class);
		commandManager2.process(new HashMap<>());
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值