spring 方法注入

package com.haut.grain.junit.test;

public  class Command {
private Object state;
public void setState(Object state) {
    this.state = state;
}
public Object getState() {
    return this.state;
}
public  void execute(){
    System.out.println("当前的状态是:"+state.toString());
}
}

以上是command类为基类

实现类UpCommand

package com.haut.grain.junit.test;

public class UpCommand extends Command{

@Override
public void execute() {
    System.out.println("向上命令的状态是:"+this.getState());
}

}

CommandManager类

package com.haut.grain.junit.test;

public abstract class CommandManager {

    public void process(Object commandState) {
        // grab a new instance of the appropriate Command interface
        Command command = createCommand();
        // set the state on the (hopefully brand new) Command instance
        command.setState(commandState);
        command.execute();
    }

    // okay... but where is the implementation of this method?
    protected abstract Command createCommand();
}

配置文件

	<bean id="upCommand" class="com.haut.grain.junit.test.UpCommand" scope="singleton"></bean>
	<bean id="commandManager" class="com.haut.grain.junit.test.CommandManager">
	<lookup-method name="createCommand" bean="upCommand"/>
	</bean>

     总结:上面就是通过createCommand方法来注入command对象,当是抽象方法时替换,如果是实现的方法了覆盖。

原文地址:https://www.cnblogs.com/maybo/p/5189497.html