Spring (06) - ApplicationContext of single instance injection into multiple instances

6 Singleton injection into ApplicationContext of multiple instances

Spring beanbeanThere are singletons beanand multiple instances in the container bean. When we need to inject a single instance beanAinto a single instance beanB, or beanAinject a multiple instance or a single instance into a multiple instance beanB, we can do it for us by configuring Springthe beancontainer. But if we need to beanAinject a multi -instance into a singleton, it is impossible to inject a multi -instance into our singleton beanBthrough 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 .SpringbeanAbeanBbeanBbeanBbeanASpringbeanAbeanBbeanAApplicationContextbeanBApplicationContextbeanB
ApplicationContextApplicationContextAware@Autowired@ResourceSpring

6.1 Implement the ApplicationContextAware interface

ApplicationContextAwareA method is defined in setApplicationContext()the interface. For those that implement the interface bean, the current Springwill 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 Springfor the current one . beanThe same is true for ApplicationContextthe same, we can tell that Springthe corresponding will be injected for us through the corresponding annotation ApplicationContext. Annotations that are automatically injected may @Resourceor 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326359984&siteId=291194637