6 Singleton injection into ApplicationContext of multiple instances
Spring bean
bean
There are singletons bean
and multiple instances in the container bean
. When we need to inject a single instance beanA
into a single instance beanB
, or beanA
inject a multiple instance or a single instance into a multiple instance beanB
, we can do it for us by configuring Spring
the bean
container. But if we need to beanA
inject a multi -instance into a singleton, it is impossible to inject a multi -instance into our singleton beanB
through configuration alone, that is, we cannot use a new one every time we use it . Because it is only initialized once, only one will be injected correspondingly . The solution is to inject one so we can get a new one from it every time we need to use it . There are two ways to inject , to implement the interface and to automatically inject through the annotation or annotation .Spring
beanA
beanB
beanB
beanB
beanA
Spring
beanA
beanB
beanA
ApplicationContext
beanB
ApplicationContext
beanB
ApplicationContext
ApplicationContextAware
@Autowired
@Resource
Spring
6.1 Implement the ApplicationContextAware interface
ApplicationContextAware
A method is defined in setApplicationContext()
the interface. For those that implement the interface bean
, the current Spring
will be passed by dispatching the corresponding setApplicationContext()
method ApplicationContext
.
public class Hello implements ApplicationContextAware {
private ApplicationContext applicationContext;
/* *
* Spring will inject the current ApplicationContext into our bean through this method
*/ public void setApplicationContext ( ApplicationContext applicationContext ) {
this . applicationContext = applicationContext;
}
}
6.2 Annotation with annotations
We know that when using annotations for configuration, we can also use annotations to tell what to inject Spring
for the current one . bean
The same is true for ApplicationContext
the same, we can tell that Spring
the corresponding will be injected for us through the corresponding annotation ApplicationContext
. Annotations that are automatically injected may @Resource
or may not be @Autowired
.
public class Hello {
private ApplicationContext applicationContext;
@Resource
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
(Note: This article is written based on Spring 4.1.0)