原型spring bean之Lookup

Posted 猿婴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原型spring bean之Lookup相关的知识,希望对你有一定的参考价值。

平时在用spring帮我们管理bean的时候,大部分情况下bean的scope都是singleton ,但是偶尔也会使用prototype,下面看这样一种情况:

// connection 对象
@Configuration
@Scope("prototype")
public class Connection 
	private String name;
	public String getName() 
		return name;
	
	public void setName(String name) 
		this.name = name;
	



// connectionService
public class ConnectionService 
	@Autowired
	public Connection connection;

	public Connection getConnection() 
		return connection;
	

Test:

AnnotationConfigApplicationContext annotationConfigApplicationContext =
    new AnnotationConfigApplicationContext(BeanConfig.class);

ConnectionService connectionService = annotationConfigApplicationContext.getBean(ConnectionService.class);
System.out.println(connectionService.getConnection()); // com.huzc.spring.ioc.autowired.Connection$$EnhancerBySpringCGLIB$$2e73c054@17f6480
System.out.println(connectionService.getConnection()); // com.huzc.spring.ioc.autowired.Connection$$EnhancerBySpringCGLIB$$2e73c054@17f6480

两次获取连接都为同一个,但是有时候这并非是我们需要的结果,我们可能需要的是两次获取的connection并非同一个。

这时我们可以使用spring提供的一个注解@Lookup来完成需求或者是实现ApplicationContextAware接口:

  • Lookup方式
@Service
public abstract class ConnectionService 
	@Lookup
	public abstract Connection connection();

	public Connection getConnection() 
		return connection();
	

// 或者下面写法
@Service
public class ConnectionService 
	@Lookup
	public Connection connection() 
		return null;
	;

	public Connection getConnection() 
		return connection();
	

  • ApplicationContextAware
@Service
public class ConnectionService implements ApplicationContextAware 
	private ApplicationContext applicationContext;

	public Connection getConnection() 
		return applicationContext.getBean(Connection.class);
	

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
		this.applicationContext = applicationContext;
	

以上是关于原型spring bean之Lookup的主要内容,如果未能解决你的问题,请参考以下文章

spring bean中子元素lookup-method和replaced-method

Spring Boot源码:循环依赖

Spring Bean的作用域以及lookup-method标签的使用

[死磕 Spring 12/43] --- IOC 之解析 bean 标签:解析自定义标签

[死磕 Spring 10/43] --- IOC 之解析 bean 标签:metalookup-methodreplace-method

spring之bean的作用域