Connect papers: the Spring core technology (6)
version 5.1.8.RELEASE
1.6 custom features Bean
The Spring Framework provides a number of interfaces can be used to customize the bean properties. In this section they are grouped as follows:
1.6.1 lifecycle callbacks
To interact with the bean life cycle management of the container can be achieved Spring InitializingBean
and DisposableBean
interfaces. The container calls the former afterPropertiesSet()
and the latter destroy()
to allow the bean to perform certain actions upon initialization and destruction of bean.
JSR-250
@PostConstruct
and@PreDestroy
notes are generally considered best practice to receive the life cycle in modern Spring application callback. Use these annotations mean that your bean will not be coupled to a specific Spring interface. For more information, see Use @PostConstruct and @PreDestroy .
In the interior, Spring Framework using BeanPostProcessor
implementations to process any callback interface it can find and call the appropriate method. If you need to customize the default functions or other Spring lifecycle behavior is not provided, they can achieve their own BeanPostProcessor
. For more information, please refer to the container extension points .
In addition to the initialization and destruction callbacks, Spring managed objects can also implement Lifecycle
an interface, so that these objects can participate in the life cycle of the container itself driven startup and shutdown procedures.
This section describes the life cycle callback interface.
Initialization callback
org.springframework.beans.factory.InitializingBean
Bean interface allows all the necessary properties entirely disposed in a container for initialization after. InitializingBean
Interface provides a method:
void afterPropertiesSet() throws Exception;
We do not recommend using the InitializingBean
interface because the code does not need to be coupled to Spring. In addition, we recommend using @PostConstruct
annotations or specify the POJO initialization method. For XML-based configuration metadata, may be used init-method
property specifies a method name None None Return parameter signatures. When using the Java configuration, you can use the @Bean
annotation initMethod
property. See reception lifecycle callbacks . Consider the following example:
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
The previous example the following example is almost identical (two lists):
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
However, the above two examples, the first example is not coupled to the code Spring.
Destruction callbacks
Implement org.springframework.beans.factory.DisposableBean
interface allows the bean to get a callback when it is included in the container is destroyed. DisposableBean
Interface provides a method:
void destroy() throws Exception;
We do not recommend the use of DisposableBean
callback interface because the code does not need to be coupled to Spring. In addition, we recommend using @PreDestroy
annotations or bean generic method definition specifies support. When using XML-based configuration metadata, you may be used <bean/>
element destroy-method
attributes. When using the Java configuration, you can use @Bean
the destroyMethod
property. See reception lifecycle callbacks . Consider the following definition:
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
Previous definition is almost identical to the following definitions:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}
However, the above two examples, the first example is not coupled to the code Spring.
You can
<bean>
elementdestroy-method
specifies a particular (estimated) value of the attribute value indicating a particular common bean class Spring automatically detectclose
orshutdown
method. (Any implementationjava.lang.AutoCloseable或java.io.Closeable
class can match.) You can also in the<beans>
elementsdefault-destroy-method
set this special (presumably) value to this behavior applies to the entire set of bean (See property default initialization and destruction methods ). Please note that this is the default behavior when using Java configuration.
The default initialization and destruction methods
When you do not use the Spring-specific InitializingBean
and DisposableBean
time to write the callback interface initialization and destruction callback methods typically used init()
, initialize()
, dispose()
like naming method. Ideally, the names of such lifecycle callback methods are consistent in the project, so that all developers use the same method name and ensure consistency.
You can configure the Spring container on each bean "look" has been named initialization and destroy callback method names. This means that, as an application developer, you can write an application class and use init()
as initialization callback, without configuring bean definitions for each init-method="init"
attribute. Spring IoC container calls this method when creating the bean (according to the previously described callback standard life cycle). This feature also enforce initialization and destruction callback methods consistent naming convention.
Suppose your initialization callback method has been named init()
and destroy your callback method is named destroy()
. Your class like the following example:
public class DefaultBlogService implements BlogService {
private BlogDao blogDao;
public void setBlogDao(BlogDao blogDao) {
this.blogDao = blogDao;
}
// this is (unsurprisingly) the initialization callback method
public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
}
You can use it in the bean similar to the following:
<beans default-init-method="init">
<bean id="blogService" class="com.something.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>
Top <beans/>
exist on the element default-init-method
attributes lead Spring IoC container will be called the bean class init
recognition method initialization callback method. When the bean is created and assembled, if the bean class has such a method, it will be called at the appropriate time.
You can also top in XML by using <beans/>
the element default-destroy-method
properties to configure destruction method callback.
If the class already has an existing bean consistent with convention callback method, may be used by itself in XML <bean/>
in init-method
and destroy-method
to override the default values attribute specifies the name of the method.
Spring container can be guaranteed to be called the configured initialization callback immediately after providing all the dependencies as bean. Therefore, it is the original bean initialization callbacks referenced on the call, which means that AOP interceptors and so have not been applied bean. First, create a completely objective bean, then the application of AOP proxy (eg, with the interceptor chain). If the target bean and proxy are defined separately, then your code can even bypass the proxy to the original target bean interaction. Therefore, the interceptor used in the init method is not appropriate, because to do so would target bean life cycle coupled to its agent, or interceptors, and the performance of direct interaction with the target bean when the original code a strange semantics.
The combined life cycle machinery
From the beginning of Spring 2.5, you have three bean life cycle behavior control options:
- In InitializingBean and DisposableBean callback interface
- Custom
init()
anddestroy()
methods @PostConstruct
And@PreDestroy
notes . You can specify a combination of these mechanisms to control the bean.
If the order of execution of a plurality of lifecycle configuration mechanism for the bean, and each is configured with a different mechanism of method names, each in accordance with the method of this configuration are listed in the annotation. However, if configured with the same name as the method of the life cycle of a plurality of mechanisms (e.g., a named initialization method
init()
), such as the one described, the method will be executed once.
When a plurality of different initialization method of the same configuration of a bean, performed in the following order:
@PostConstruct
Annotated methodInitializingBean
DefinedafterPropertiesSet()
callback interface- Custom configuration
init()
method
Destruction method calls in the same order:
@PreDestroy
Annotated methodDisposableBean
Defineddestroy()
callback interface- Custom configuration
destroy()
method
Startup and Shutdown callback
Lifecycle
Interfaces for any object that has its own life cycle requirements (such as start and stop some background processes) defines the basic methods:
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
Any Spring managed objects can implement Lifecycle
interfaces. Then, when ApplicationContext
upon receiving the start and stop signals (e.g., for run-time stop / restart scenes), it calls defined in the context of cascaded Lifecycle
all implemented. By delegating it to LifecycleProcessor
be implemented, as shown in the following list:
public interface LifecycleProcessor extends Lifecycle {
void onRefresh();
void onClose();
}
Please note that LifecycleProcessor
it is itself Lifecycle
the expansion interface. It also adds two other ways to refresh and close in response to context.
Please note that the conventional
org.springframework.context.Lifecycle
interface is a simple protocol explicitly start and stop notice, does not mean that automatically start when the context refresh. To fine-grained control over specific bean automatic start (including the start-up phase), consider implementingorg.springframework.context.SmartLifecycle
.
Also, please note that before destroying stop can not be guaranteed to receive notification. When conventional closed, all theLifecycle
bean before the start of the first recipients of general destruction callback stop notice. However, in the context of the life cycle of hot flush or suspended when trying to refresh, call the only method of destruction.
Startup and shutdown call order is important. If there is "dependency" relationship between any two objects, the relying party begins after its dependencies, and stops before its dependencies. However, sometimes, direct dependence is unknown. You may only know the object of some type should start before another one type of object. In these cases, SmartLifecycle
the interface defines another option, i.e. the interface parent Phased
methods defined on getPhase()
. The following shows the Phased
definition of the interface:
public interface Phased {
int getPhase();
}
The following shows the SmartLifecycle
definition of the interface:
public interface SmartLifecycle extends Lifecycle, Phased {
boolean isAutoStartup();
void stop(Runnable callback);
}
At startup, the object has the lowest level of first start. When stopped, follow the reverse order. Therefore, to achieve SmartLifecycle
the object and getPhase()
return Integer.MIN_VALUE
will be the first to start and last stop of the object. In another area, the phase value Integer.MAX_VALUE
will indicate the object should last start and first stop (probably because it depends on other processes running). When considering the phase value, it is also important to know that for any "normal" does not achieve SmartLifecycle
the Lifecycle
object, the default value 0
. Therefore, any negative value indicates that the object phase should start (and stop after their) until these standard components. Any positive phase values are reversed.
SmartLifecycle
Stop-defined method accepts a callback. Any implementation must call the callback after completion of the closing process of the implementation run()
method. This will enable asynchronous closed when necessary, because LifecycleProcessor
the default implementation of the interface DefaultLifecycleProcessor
to wait timeout value target group within each period to invoke the callback. The default timeout of 30 seconds per stage. Can be named in this context is defined lifecycleProcessor
to override the default lifetime processor instance bean. If you want to modify the timeout, then define the following will suffice:
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
<!-- timeout value in milliseconds -->
<property name="timeoutPerShutdownPhase" value="10000"/>
</bean>
As previously described, LifecycleProcessor
the interface defines the method used to refresh and closing callback context. The latter procedure similar to the display driving off call stop()
, but it only occurs when the context is closed. On the other hand, 'refresh' Callback enabled SmartLifecycle
another feature of the bean. When you refresh the context (after instantiate and initialize all objects), calls the callback. In this case, the default life cycle of the processor checks each SmartLifecycle
object isAutoStartup()
boolean value returned by the method. If it is true
, then the object was to start, rather than waiting for an explicit call context or its own start()
method (refresh different context, the context does not start automatically occur in the context of the standard implementation). phase
Value determines the startup sequence according to any preceding relation "dependent" type and.
In non-Web applications gracefully shut down the Spring IoC container
This section applies only to non-Web applications. Spring Web-based
ApplicationContext
implementations have been associated with the code can be normally closed when the associated container Spring IoC Web application is closed.
If you are using Spring IoC container in a non-Web application environment (for example, in a client desktop environment), use the JVM registered shutdown hook. Doing so ensures that normal shutdown and calls on the relevant methods of destruction singleton bean, in order to release all resources. You must properly configure and implement these destruction callback.
To register a shutdown hook, call the ConfigurableApplicationContext
statement on the interface registerShutdownHook()
method, as shown in the following example:
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Boot {
public static void main(final String[] args) throws Exception {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
// add a shutdown hook for the above context...
ctx.registerShutdownHook();
// app runs here...
// main method exits, hook is called prior to the app shutting down...
}
}
1.6.2 ApplicationContextAware
andBeanNameAware
When ApplicationContext
created to achieve org.springframework.context.ApplicationContextAware
when the interface object instance, will ApplicationContext
provide a reference to that instance. The following list shows the ApplicationContextAware
definition of the interface:
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
Thus, the bean can ApplicationContext
be a known reference in this subclass conversion interface or via an interface (e.g. other features disclosed ConfigurableApplicationContext
,) created programmatically manipulate them ApplicationContext
. One use is to be programmed to retrieve other bean. This feature is sometimes useful. However, in general it should be avoided, because the collaborators is provided to the bean and the code to Spring coupled to the inverted control does not follow the style as an attribute. ApplicationContext
Other ways to provide access to file resources, events, and access published applications MessageSource
. These additional features ApplicationContext
of the additional functionality description.
Starting Spring 2.5, automatic assembly acquiring another ApplicationContext
reference method. "Traditional" constructor
and byType
automated assembly mode (e.g., automatic assembling collaborators said) may be respectively constructor arguments or parameters provided setter method ApplicationContext
type dependent. For greater flexibility, and the ability to automatically assemble multi-parameter fields and methods of obtaining, use the new annotation-based auto assembly function. If the relevant fields, with a constructor or method @Autowired
annotated needs and ApplicationContext
types, ApplicationContext
will automatically load a field, or process parameters constructor argument. For more information, see use@Autowired
.
When ApplicationContext
to create an implementation org.springframework.beans.factory.BeanNameAware
when the class interface, will provide its associated object class definitions corresponding to the name of the reference. The following list shows the BeanNameAware
definition of the interface:
public interface BeanNameAware {
void setBeanName(String name) throws BeansException;
}
After the correction of ordinary bean property, but before an initialization callback, for example InitializingBean
, afterPropertiesSet
or a custom initialization method.
1.6.3 Other Aware
interfaces
In addition ApplicationContextAware
, and BeanNameAware
(in the before discussed), Spring provides a broad Aware
pullback to allow bean container indicated that they need some infrastructure dependencies. As a general rule, the name represents the dependency type. The following table summarizes the most important Aware
interfaces:
name | Inject dependencies | description |
---|---|---|
ApplicationContextAware | statement ApplicationContext |
ApplicationContextAware with BeanNameAware |
ApplicationEventPublisherAware | ApplicationContext time includes publisher | Other features of the ApplicationContext |
BeanClassLoaderAware | Class loader for loading classes bean | Bean instantiation |
BeanFactoryAware | Statement BeanFactory | ApplicationContextAware with BeanNameAware |
BeanNameAware | Statement name of the bean | ApplicationContextAware with BeanNameAware |
BootstrapContextAware | Container resource adapter running BootstrapContext . ApplicationContext usually available only in the instance supports JCA |
JCA CCI |
LoadTimeWeaverAware | weaver defined in the class definition for processing when loading | When weaving with AspectJ loaded in the Spring Framework |
MessageSourceAware | For parsing the message policies configured (parameter support and internationalization) | Other features of the ApplicationContext |
NotificationPublisherAware | Spring JMX notification Publisher | Notice |
ResourceLoaderAware | For low-level access to the resource configuration loader | Resources |
ServletConfigAware | The current container operation ServletConfig . Web-only ApplicationContext effective in |
Spring MVC |
ServletContextAware | The current container operation ServletContext . Web-only ApplicationContext effective in |
Spring MVC |
Note again that the use of these interfaces will make your code and API coupling Spring, and does not follow the IOC standards. Therefore, we recommend that they need to access the container programmatically infrastructure bean.
- My CSDN: https://blog.csdn.net/liweitao7610
- My blog garden: https://www.cnblogs.com/aotian/
- My Jane book: https://www.jianshu.com/u/6b6e162f1fdc