Skip to content

Instantly share code, notes, and snippets.

@sizovs
Created December 7, 2024 10:42
Show Gist options
  • Save sizovs/30c5a72852f3a509c6bcd5ff783a637e to your computer and use it in GitHub Desktop.
Save sizovs/30c5a72852f3a509c6bcd5ff783a637e to your computer and use it in GitHub Desktop.
import com.google.common.collect.ForwardingList;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
interface Bean { }
@Component
@Scope(SCOPE_PROTOTYPE)
class JavaBean implements Bean { }
@Component
@Scope(SCOPE_PROTOTYPE)
class CoffeeBean implements Bean { }
@Component
@Scope(SCOPE_PROTOTYPE)
class RocketBean implements Bean { }
@Component
public class Beans extends ForwardingList<Bean> {
private final ObjectProvider<Bean> beans; // can be multiple sources
public Beans(ObjectProvider<Bean> beans) {
this.beans = beans;
}
@Override
protected List<Bean> delegate() {
return beans.stream().toList(); // can be pre-filtered, for example
}
}
class CoffeeShop {
@Autowired
Beans beans; // at this point, Spring has not initialized the beans.
void accessBeansLazily() {
beans.forEach(System.out::println); // initialization happens here.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment