Skip to content

Instantly share code, notes, and snippets.

@milovtim
Last active January 15, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milovtim/77d77187839aa8ed447ab6e6b0bc0da6 to your computer and use it in GitHub Desktop.
Save milovtim/77d77187839aa8ed447ab6e6b0bc0da6 to your computer and use it in GitHub Desktop.
Demonstration on bean definitions inheritanse between parent-child contexts
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.support.GenericGroovyApplicationContext
interface ServiceInParent {
String invokeParent()
}
class ChildService {
ServiceInParent serviceInParent
String invokeChild() {
return serviceInParent.invokeParent()
}
}
class ServiceInParentImpl1 implements ServiceInParent{
@Override
String invokeParent() {
return 'parent impl-1'
}
}
class ServiceInParentImpl2 implements ServiceInParent{
@Override
String invokeParent() {
return 'parent impl-2'
}
}
////////////
def parent = new GenericGroovyApplicationContext()
parent.reader.beans {
serviceInParent(ServiceInParentImpl1)
}
parent.refresh()
def child = new GenericGroovyApplicationContext()
child.reader.beans {
serviceInParent(ServiceInParentImpl2) //comment this line to see than parent bean used
childService(ChildService) {
serviceInParent = ref('serviceInParent')
}
}
child.setParent(parent)
child.refresh()
child.getBean(ChildService).invokeChild() //parent impl-(1|2) depends on whether the bean in child context was registered (see line 39)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment