平时在用spring帮我们管理bean的时候,大部分情况下bean的scope都是singleton
,但是偶尔也会使用prototype,下面看这样一种情况:
@Configuration
@Scope("prototype")
public class Connection {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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());
System.out.println(connectionService.getConnection());
两次获取连接都为同一个,但是有时候这并非是我们需要的结果,我们可能需要的是两次获取的connection并非同一个。
这时我们可以使用spring提供的一个注解@Lookup来完成需求或者是实现ApplicationContextAware接口:
@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();
}
}
@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;
}
}
|