Analysis of scope and life cycle principle of spring framework beam

Time:2020-7-29

This article mainly introduces the spring framework bean scope and life cycle principle analysis, the article through the example code introduction is very detailed, has certain reference learning value to everybody’s study or work, needs the friend may refer to

Scope of spring beand

When it is set to singleton, it means that a class can only have one instance. When it is applied again, the same instance is returned

You can see that the hashcode values of the two bean instances are the same, indicating that the same instance is applied here
When you set the scope of the bean to prototype and run it again, you can see that two different bean instances are applied

At present, only the prototype scope and singleton scope have been learned, and the rest will be learned after waiting

The life cycle of spring beans

1. The process of defining the configuration XML file

2. Initialize the IOC container to instantiate the bean

3. Use

4. Destroy all bean instances created by the bean container when the destruction of the IOC container stops

There are three ways to initialize and destroy

1. Implement the interface, initializingbean, disposablebean

2. Define init method and destroy method in each bean

3. Define default init and default destroy methods in XML configuration file


/*
 * public void defautinit() { System.out.println("Bean defaut Init." +
 * this.hashCode()); }
 * 
 * public void defautdestroy() { System.out.println("Bean defaut destroy." +
 * this.hashCode()); }
 */


/*
 * @Override public void destroy() throws Exception {
 * System.out.println("Bean destory."+this.hashCode()); }
 * 
 * @Override public void afterPropertiesSet() throws Exception {
 * System.out.println("Bean init."+this.hashCode()); }
 */

/*
 * public void start() { System.out.println("Bean start."+this.hashCode()); }
 * 
 * public void stop() { System.out.println("Bean stop."+this.hashCode()); }
 */

The initialization and destruction methods defined by the interface have higher priority than those defined in the bean,

The default method of XML has the lowest priority. It can not even be implemented in the bean and will not report an error. If the other two methods are implemented, they will be overridden

If the init and destroy methods are set in the bean, they must be implemented, otherwise the startup will fail

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.