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<>());
	}
}
相关推荐
hello 早上好3 小时前
深入 Spring 条件化配置底层:从硬编码到通用注解的实现原理
java·后端·spring
亚林瓜子3 小时前
Spring中Date日期序列化与反序列化中格式设置
java·后端·spring·jackson·date
哞哞不熬夜7 小时前
JavaEE--Spring MVC
spring·java-ee·mvc
Java水解8 小时前
深入剖析Spring Boot依赖注入顺序:从原理到实战
后端·spring
椎4959 小时前
web后端开发——原理
spring boot·spring·mybatis
Wade_Crab10 小时前
第二章:动态 Prompt 管理与多科室智能问答系统
人工智能·spring·prompt
技术猴小猴11 小时前
如何使用Python实现LRU缓存
python·spring·缓存
hrrrrb14 小时前
【Spring Security】Spring Security 密码编辑器
java·hive·spring
Elsa️7461 天前
个人项目开发(1):使用Spring Secruity实现用户登录
java·后端·spring
码界奇点1 天前
Spring Web MVC构建现代Java Web应用的基石
java·前端·spring·设计规范