Java学习笔记(十三)-Spring(六)

**

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());  
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值