欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring中单例中获取新的bean实例

程序员文章站 2024-01-06 21:55:16
...

spring中配置的单例实例中,如果需要每次获取新的属性对象,有两种方式。1、采用配置文件中的lookup-method元素   2、实现BeanFactoryAware接口。

public interface AxeInter {
	public void chop();
}

 

public class StoneAxe implements AxeInter {
	@Override
	public void chop() {
		System.out.println("石头斧头");
	}
}

 

<bean id="axe" class="springTest.impl.StoneAxe" scope="prototype">
</bean>

 

 

  1.  采用配置文件中的lookup-method元素

 

public abstract class UserService2 {
	public abstract AxeInter getAxe();
}

 注意:没有get、set方法

 

 

<bean id="userService2" class="springTest.impl.UserService2">
		<lookup-method name="getAxe" bean="axe"/>
	</bean>

 

public class CopyOfSpringTest1 {

	private ApplicationContext context = null;
	

	@Before
	public void before(){
		context = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	@Test
	public void testMoreInstanceInSingleInstance(){
		UserService2 userService = context.getBean("userService2", UserService2.class);
		System.out.println(userService);
		System.out.println(userService.getAxe());
		
		UserService2 userService2 = context.getBean("userService2", UserService2.class);
		System.out.println(userService2);
		System.out.println(userService2.getAxe());
	}
}

 

   2.实现BeanFactoryAware接口。

public class UserService implements BeanFactoryAware{

	private AxeInter axe;
	private BeanFactory beanFactory;
	
	public AxeInter getAxe() {
		this.axe = (AxeInter)beanFactory.getBean("axe");
		return axe;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}
}

 注意:没有axe的set方法

<bean id="userService" class="springTest.impl.UserService">
	</bean>

 

@Test
	public void testMoreInstanceInSingleInstance(){
		UserService userService = context.getBean("userService", UserService.class);
		System.out.println(userService);
		System.out.println(userService.getAxe());
		
		UserService userService2 = context.getBean("userService", UserService.class);
		System.out.println(userService2);
		System.out.println(userService2.getAxe());
	}

 

 

上一篇:

下一篇: