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

使用lookup-method:

一、实体类:

复制代码
package cn.edu.tju.domain2;

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.domain2;

import java.util.HashMap;

public abstract class CommandManager {
	public Object process(Object commandState) {
		// grab a new instance of the appropriate Command interface
		Command command = createCommand();
		System.out.println("hash: " + command.hashCode());
		// set the state on the (hopefully brand new) Command instance
		command.setState(new HashMap<String, Object>());
		return command.execute();
	}
	// okay... but where is the implementation of this method?
	protected abstract Command createCommand();

}

二、配置文件:

复制代码
<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.domain2.CommandManager" id="commandManager"  >
		<lookup-method bean="command" name="createCommand"/>
	</bean>

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

</beans>

三、主类:

复制代码
package cn.edu.tju;

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

import java.util.HashMap;

public class TestDiffScope2 {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test8.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<>());
	}
}
相关推荐
Coder_Boy_9 小时前
技术发展的核心规律是「加法打底,减法优化,重构平衡」
人工智能·spring boot·spring·重构
方见华Richard18 小时前
世毫九量子原住民教育理念全书
人工智能·经验分享·交互·原型模式·空间计算
张3蜂21 小时前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
Coder_Boy_21 小时前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
7哥♡ۣۖᝰꫛꫀꪝۣℋ1 天前
Spring-cloud\Eureka
java·spring·微服务·eureka
一灰灰blog1 天前
Spring AI中的多轮对话艺术:让大模型主动提问获取明确需求
数据库·人工智能·spring
Java水解1 天前
【JAVA 进阶】Spring AOP核心原理:JDK与CGLib动态代理实战解析
后端·spring
方见华Richard1 天前
方见华个人履历|中英双语版
人工智能·经验分享·交互·原型模式·空间计算
暮色妖娆丶1 天前
Spring 源码分析 BeanFactoryPostProcessor
spring boot·spring·源码
有位神秘人1 天前
kotlin与Java中的单例模式总结
java·单例模式·kotlin