Spring Getting Started 07 - Bean Life Cycle

xiaoxiao2021-03-06  42

Getting Started 07 - Bean Life Cycle

In Spring, the examples obtained from BeanFactory are Singleton, and the preset is to maintain an instance, and there is no problem for a single-in-inteprexic program, but for multi-execution, you must notice the execution. To be safe, you can also set up a new instance each time you get beans from BeanFactory, for example:

Singleton preset is TRUE, which will generate a new instance when it is set to false. BeanFactory is responsible for the lifecycle of bean, including the generation and destruction of Bean, bean's creation mode (whether it is singleton), bean's attribute setting, dependency established, etc. If you want to make some things in a stage of the lifecycle of the bean, there are several ways, the first way is the related interface provided by Spring, through the actual org.springframework.beansFactory.InitializingBean, Org.SpringFramework.beans.Factory.disposableBean, you can create some things when you create and destroy:

Public interface initializingbean {

Void afterpropertiesSset () throws Exception;

}

Public interface disposablebean {

Void destroy () throws exception;

}

The actual interface makes Spring's specific interface invading the BEAN's work, which is not a good practice. Considering the replacement of Beans, you can consider the initialization and destruction of unified beans, and declare in the bean definition file Use these methods when initialized or destroying beans:

INIT-method = "init"

DESTROY-METHOD = "Destroy">

When acting as a bean, just add these methods, for example:

Public class hellobean {

Public void init () {

....

}

....

Public void destroy () {

....

}

}

The benefit of this is that any Spring-specific interface can be not introduced so that Bean can easily get from the Spring framework, as long as the other frame you use can support the initialization and destruction method of your own customs, beans do not need any Modifying, however, in fact, in fact, depending on the container, the container must have the ability to call these methods, but the names of these methods can be determined by us, without having to implement a specific interface. In addition to the above two ways, you can also make some similar initialization actions in BEAN's construction or setter, which makes the bean does not rely on specific interfaces or container features, but the action of destruction is more troublesome, because Finalize The time to perform is determined by the GC, you can only put some destruction of the destruction of the real-time demand.

转载请注明原文地址:https://www.9cbs.com/read-60923.html

New Post(0)