**
Spring的非单例注入实例
放弃IOC
接口类:
package pojo;
public interface Command {
public Object execute();
}
实现类:
package pojo;
public class AsyncCommand implements Command {
@Override
public Object execute(){
return this;
}
}
**
业务类:
ApplicationContextAware和BeanFactoryAware差不多,用法也差不多,实现了ApplicationContextAware接口的对象会拥有
package pojo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class CommandManager implements ApplicationContextAware {
private ApplicationContext applicationContext;
public Object process(){
Command command=createCommand();
return command.execute();
}
private Command createCommand(){
return (Command)this.applicationContext.getBean("asyncCommand");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext = applicationContext;//获得该ApplicationContext引用
}
}
配置文件:
<?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="pojo.CommandManager">
</bean>
</beans>
测试
package test;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.CommandManager;
public class testprototype {
private ApplicationContext context;
public void setUp() throws Exception {
context = new ClassPathXmlApplicationContext("beans-dropioc.xml");
}
public static void main(String args[]){
ApplicationContext context1 = new ClassPathXmlApplicationContext("beans-dropioc.xml");
CommandManager manager=(CommandManager)context1.getBean("commandManager",CommandManager.class);
System.out.println("第一执行process,Command的地址是:" + manager.process());
System.out.println("第二执行process,Command的地址是:" + manager.process());
}
}