原型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;
	}
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>