Java學習筆記(十四)-Spring(七)

LookUp實現非單例注入實例

承接上文(https://blog.csdn.net/qq_36328413/article/details/100526288)的AsyncCommandManager
首先創建一個lookup包然後創建一個CommandManager抽象類

package lookup;
import pojo.Command;

public abstract class CommandManager {
	//模擬業務處理的方法
	public Object process(){
		Command command=createCommand();
		return command.execute();
	}
	protected abstract Command createCommand();
}

配置文件:beans-lookup.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
    <!-- 通過scope="prototype"界定該bean是多例的 -->  
    <bean id="asyncCommand" class="pojo.AsyncCommand"  
        scope="prototype"></bean>  
          
    <bean id="commandManager" class="lookup.CommandManager">    
            <lookup-method name="createCommand" bean="asyncCommand"/>    
        </bean>  
</beans>   

標籤中的name屬性就是commandManager Bean的獲取Command實例(AsyncCommand)的方法,也就createCommand方法,bean屬性是要返回哪種類型的Command的,這裏是AsyncCommand。Spring自動幫我們實現了createCommand
創建測試類:testlookup

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import lookup.CommandManager;

public class testlookup {

	public static void main(String args[]){
		ApplicationContext context1 = new ClassPathXmlApplicationContext("beans-lookup.xml"); 
		CommandManager manager=(CommandManager)context1.getBean("commandManager",CommandManager.class);
		System.out.println("第一執行process,Command的地址是:" + manager.process());  
        System.out.println("第二執行process,Command的地址是:" + manager.process());  
		
	}
}

結果如下:
在這裏插入圖片描述
Lookup易於擴展,更符合Ioc規則,所以儘量採用這種方式實現非單例注入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章