Spring core technology (7)

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 InitializingBeanand DisposableBeaninterfaces. 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 @PostConstructand @PreDestroynotes 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 BeanPostProcessorimplementations 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 Lifecyclean 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.InitializingBeanBean interface allows all the necessary properties entirely disposed in a container for initialization after. InitializingBeanInterface provides a method:

void afterPropertiesSet() throws Exception;

We do not recommend using the InitializingBeaninterface because the code does not need to be coupled to Spring. In addition, we recommend using @PostConstructannotations or specify the POJO initialization method. For XML-based configuration metadata, may be used init-methodproperty specifies a method name None None Return parameter signatures. When using the Java configuration, you can use the @Beanannotation initMethodproperty. 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.DisposableBeaninterface allows the bean to get a callback when it is included in the container is destroyed. DisposableBeanInterface provides a method:

void destroy() throws Exception;

We do not recommend the use of DisposableBeancallback interface because the code does not need to be coupled to Spring. In addition, we recommend using @PreDestroyannotations or bean generic method definition specifies support. When using XML-based configuration metadata, you may be used <bean/>element destroy-methodattributes. When using the Java configuration, you can use @Beanthe destroyMethodproperty. 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>element destroy-methodspecifies a particular (estimated) value of the attribute value indicating a particular common bean class Spring automatically detect closeor shutdownmethod. (Any implementation java.lang.AutoCloseable或java.io.Closeableclass can match.) You can also in the <beans>elements default-destroy-methodset 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 InitializingBeanand DisposableBeantime 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-methodattributes lead Spring IoC container will be called the bean class initrecognition 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-methodproperties 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-methodand destroy-methodto 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:

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 method
  • InitializingBeanDefined afterPropertiesSet()callback interface
  • Custom configuration init()method

Destruction method calls in the same order:

  • @PreDestroy Annotated method
  • DisposableBeanDefined destroy()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 Lifecycleinterfaces. Then, when ApplicationContextupon receiving the start and stop signals (e.g., for run-time stop / restart scenes), it calls defined in the context of cascaded Lifecycleall implemented. By delegating it to LifecycleProcessorbe implemented, as shown in the following list:

public interface LifecycleProcessor extends Lifecycle {

    void onRefresh();

    void onClose();
}

Please note that LifecycleProcessorit is itself Lifecyclethe expansion interface. It also adds two other ways to refresh and close in response to context.

Please note that the conventional org.springframework.context.Lifecycleinterface 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 implementing org.springframework.context.SmartLifecycle.
Also, please note that before destroying stop can not be guaranteed to receive notification. When conventional closed, all the Lifecyclebean 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, SmartLifecyclethe interface defines another option, i.e. the interface parent Phasedmethods defined on getPhase(). The following shows the Phaseddefinition of the interface:

public interface Phased {

    int getPhase();
}

The following shows the SmartLifecycledefinition 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 SmartLifecyclethe object and getPhase()return Integer.MIN_VALUEwill be the first to start and last stop of the object. In another area, the phase value Integer.MAX_VALUEwill 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 SmartLifecyclethe Lifecycleobject, 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.

SmartLifecycleStop-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 LifecycleProcessorthe default implementation of the interface DefaultLifecycleProcessorto 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 lifecycleProcessorto 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, LifecycleProcessorthe 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 SmartLifecycleanother 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 SmartLifecycleobject 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). phaseValue 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 ApplicationContextimplementations 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 ConfigurableApplicationContextstatement 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 ApplicationContextAwareandBeanNameAware

When ApplicationContextcreated to achieve org.springframework.context.ApplicationContextAwarewhen the interface object instance, will ApplicationContextprovide a reference to that instance. The following list shows the ApplicationContextAwaredefinition of the interface:

public interface ApplicationContextAware {

    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

Thus, the bean can ApplicationContextbe 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. ApplicationContextOther ways to provide access to file resources, events, and access published applications MessageSource. These additional features ApplicationContextof the additional functionality description.

Starting Spring 2.5, automatic assembly acquiring another ApplicationContextreference method. "Traditional" constructorand byTypeautomated assembly mode (e.g., automatic assembling collaborators said) may be respectively constructor arguments or parameters provided setter method ApplicationContexttype 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 @Autowiredannotated needs and ApplicationContexttypes, ApplicationContextwill automatically load a field, or process parameters constructor argument. For more information, see use@Autowired .

When ApplicationContextto create an implementation org.springframework.beans.factory.BeanNameAwarewhen the class interface, will provide its associated object class definitions corresponding to the name of the reference. The following list shows the BeanNameAwaredefinition 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, afterPropertiesSetor a custom initialization method.

1.6.3 Other Awareinterfaces

In addition ApplicationContextAware, and BeanNameAware(in the before discussed), Spring provides a broad Awarepullback 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 Awareinterfaces:

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 ApplicationContexteffective in Spring MVC
ServletContextAware The current container operation ServletContext. Web-only ApplicationContexteffective 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.

Guess you like

Origin www.cnblogs.com/aotian/p/11445886.html