Spring Learning Notes (iii)

Source: Internet
Author: User
Tags class definition
Combining lifecycle Mechanisms

As of Spring 2.5, have three options for controlling beans lifecycle Behavior:theinitializingbean and Disposablebean C Allback interfaces; Custominit () Anddestroy () methods; and The@postconstruct and @PreDestroy annotations. You can combine this mechanisms to control a given bean.

Note

If multiple lifecycle mechanisms are configured for a beans, and each mechanism was configured with a different method name, Then each configured to executed in the order listed below. However, if the same method name was Configured-for Example,init () for a initialization method-for more than one of th ESE lifecycle mechanisms, which is executed once, as explained in the preceding section.

Call Order

Multiple lifecycle mechanisms configured for the same beans, with different initialization methods, are called as follows:

Methods Annotated with @PostConstruct

Afterpropertiesset () as defined by Theinitializingbean callback interface

A Custom Configured init () method

Destroy methods are called in the same order:

Methods Annotated with @PreDestroy

Destroy () as defined by Thedisposablebean callback interface

A Custom configured Destroy () method


shutting down the Spring IoC container gracefully in non-web applications

Note

This section applies only to Non-web applications. Spring ' s web-based applicationcontext implementations already have code in place to shut down the Spring IoC container GRA Cefully the relevant web application is shut down.

If you are the using Spring ' s IoC container in a non-web application environment; For example, in a rich-client desktop environment; Your register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy-methods on your singleton beans Are released. Course, you must still configure and implement these destroy callbacks.

To register a shutdown hook, and call the "Registershutdownhook" () method This is declared on Theabstractapplicationcontext Class

Import Org.springframework.context.support.AbstractApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Public final class Boot {public

  static void Main (final string[] args) throws Exception {
      Abstractapplicationconte XT CTX
          = new Classpathxmlapplicationcontext (new String []{"Beans.xml"});

      Add a shutdown hook for the "above" context ... 
      Ctx.registershutdownhook ();

      App runs

      ... Main method exits, the hook is called prior to the app shutting down ...
  }
5.6.2 Applicationcontextaware Andbeannameaware

When a applicationcontext creates a class that implements Theorg.springframework.context.ApplicationContextAware interface, the class is provided with a reference to Thatapplicationcontext.

Public interface Applicationcontextaware {

  void Setapplicationcontext (ApplicationContext applicationcontext) Throws Beansexception;
}

Thus beans can manipulate programmatically applicationcontext that created them, through Theapplicationcontext Interfa CE, or by casting the "reference to a known subclass of" interface, such asconfigurableapplicationcontext, which expose s additional functionality. One use would is the programmatic retrieval of the other beans. Sometimes this capability is useful; However, should avoid it, because it couples the code to Spring and does not follow the inversion of contro L style, where collaborators are provided to beans as properties. Other methods of the ApplicationContext provide access to file resources, publishing application events, and accessing a M Essagesource. These additional features are described in section 5.14, "Additional capabilities of the ApplicationContext"

As of Spring 2.5, autowiring is another alternative to obtain reference to Theapplicationcontext. The "traditional" constructor Andbytype autowiring modes (as described insection 5.4.5, "autowiring collaborators") can provide a dependency of typeapplicationcontext for a constructor argument or setters method parameter, respectively. For more flexibility, including the ability to Autowire fields and multiple parameter, use the new methods D autowiring features. If you did, Theapplicationcontext is autowired to field a, constructor argument, or method parameter this is expecting th Eapplicationcontext type if the field, constructor, or method in question carries the@autowired annotation. For more information, seesection 5.9.2, "@Autowired".

When a applicationcontext creates a class that implements the Org.springframework.beans.factory.BeanNameAware interface , the class is provided with a reference to the name defined in its associated object definition.

Public interface Beannameaware {

  void Setbeanname (string name) throws Beansexception;
}

The callback is invoked after population's normal bean properties but before an initialization callback such Asinitializi Ngbeansafterpropertiesset or a custom init-method.


5.7 Bean definition inheritance

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and Co Ntainer-specific information such as initialization method, static factory method name, and. A child bean definition inherits configuration the data from a parent definition. The child definition can override some values, or add others, as needed. Using parent and child bean definitions can save a lot of typing. Effectively, this is a form of templating.

If you are work with a ApplicationContext interface programmatically, child bean definitions are from represented by Thechildbeand Efinition class. Most users do not work with them at this level, instead configuring beans definitions declaratively in something like thecl Asspathxmlapplicationcontext. When to use the xml-based configuration metadata, you are indicate a child bean definition by using theparent attribute, specifyi ng the parent bean as the value of this attribute.

<bean id= "Inheritedtestbean" abstract= "true"
    class= "Org.springframework.beans.TestBean" >
  < Property name= ' name ' value= ' parent '/>
  <property name= ' age ' value= ' 1 '/>
</bean>

<bean Id= "Inheritswithdifferentclass"
      class= "Org.springframework.beans.DerivedTestBean"
      parent= " Inheritedtestbean " init-method=" Initialize ">

  <property name=" name "value=" override "/>
  <! -The Age property value of 1 would be inherited from  parent-->

</bean>

A Child bean definition uses the beans class from the parent definition if none specified, but can also override it. In the "latter case", the child bean class must being compatible with the parent, which, it must accept the parent ' s property Values.

A Child Bean definition inherits constructor argument values, property values, and how to overrides from the parent, with The option to add new values. Any initialization method, destroy method, And/orstatic factory method Settings This you specify'll override the Corresp Onding parent settings.

The remaining settings are always taken from the child definition:depends On,autowire the mode,dependency check,singleton,scop E,lazy init.

The preceding example explicitly marks the parent bean definition as abstract by using Theabstract attribute. If The parent definition does not specify a class, explicitly marking the parent bean definition asabstract is required, a S follows:

<bean id= "Inheritedtestbeanwithoutclass" abstract= "true" > <property "name=" Name "value=" parent "/> <property name=" Age "value=" 1 "/> </bean> <bean id=" Inheritswithclass "class= "Org.springframework.beans.DerivedTestBean" parent= "Inheritedtestbeanwithoutclass" init-method= "Initialize" > & Lt;property name= "name" value= "override"/> <!--age would inherit the value of 1 from the parent bean definition--&
Gt </bean> 

The parent bean cannot to be instantiated to its own because it are incomplete, and it is also explicitly marked Asabstract . When a definition isabstract like this, it's usable only as a pure template beans definition that serves as a parent Defin Ition for the child definitions. Trying to the such anabstract parent Bean on its own, by referring to it as a ref the another bean or doing an exp Licitgetbean () call with the parent bean ID, returns an error. Similarly, the container ' s internalpreinstantiatesingletons () method ignores beans definitions that are as abstract .

Note

ApplicationContext pre-instantiates all singletons by default. Therefore, it is important (in least for singleton beans) This if you have a (parent) beans definition which you intend to Use only as a template, and this definition specifies a class, your must make sure to set the abstract attribute Totrue, OT Herwise The application context would actually (attempt to) Pre-instantiate theabstract Bean.



5.6.3 Other aware interfaces

Besides Applicationcontextaware and Beannameaware discussed above, Spring offers a range of aware interfaces that allow is Ans to indicate to the container that they require a certaininfrastructure dependency. The most importantaware interfaces are summarized Below-as A, the name is a good indication of the Dependen CY Type:
Table 5.4. Aware Interfaces

Name injected Dependency explained in ...

Applicationcontextaware

Declaring ApplicationContext

Section 5.6.2, "Applicationcontextaware and Beannameaware"

Applicationeventpublisheraware

Event publisher of the enclosing ApplicationContext

Section 5.14, "Additional capabilities of Theapplicationcontext"

Beanclassloaderaware

Class loader used to load the bean classes.

Section 5.3.2, "Instantiating beans"

Beanfactoryaware

Declaring beanfactory

Section 5.6.2, "Applicationcontextaware and Beannameaware"

Beannameaware

Name of the declaring bean

Section 5.6.2, "Applicationcontextaware and Beannameaware"

Bootstrapcontextaware

Resource Adapter Bootstrapcontext the container runs in. Typically available only in JCA awareapplicationcontexts

Chapter 25,JCA CCI

Loadtimeweaveraware

Defined Weaver for processing class definition in load time

Section 9.8.4, "Load-time weaving with AspectJ in the Spring Framework"

Messagesourceaware

Configured strategy for resolving messages (with support for parametrization and internationalization)

Section 5.14, "Additional capabilities of Theapplicationcontext"

Notificationpublisheraware

Spring JMX Notification Publisher

Section 24.7, "Notifications"

Portletconfigaware

Current Portletconfig the container runs in. Valid only in a web-aware springapplicationcontext

Chapter 20,portlet MVC Framework

Portletcontextaware

Current Portletcontext the container runs in. Valid only in a web-aware springapplicationcontext

Chapter 20,portlet MVC Framework

Resourceloaderaware

Configured loader for low-level access to resources

Chapter 6,resources

Servletconfigaware

Current ServletConfig the container runs in. Valid only in a web-aware springapplicationcontext

Chapter 17,web MVC Framework

Servletcontextaware

Current ServletContext the container runs in. Valid only in a web-aware springapplicationcontext

Chapter 17,web MVC Framework


Note again that usage of those interfaces ties your code to the Spring API and does not follow the inversion of control St Yle. As such, they are recommended for infrastructure this beans require access to the programmatic.
5.8.1 customizing Beans using a beanpostprocessor

The Beanpostprocessor interface defines callback methods, can implement to provide your (or own the override Iner ' s default) instantiation logic, dependency-resolution logic, and so forth. If you are want to implement some custom logic after the Spring container finishes instantiating, configuring, and Initializin G A bean, can plug in one or more beanpostprocessor implementations.

You can configure multiple Beanpostprocessor instances, and your can control the order in which Thesebeanpostprocessors EXE Cute by setting Theorder. You can set this property only if Thebeanpostprocessor implements Theordered interface; If you are write your ownbeanpostprocessor you should consider implementing theordered the interface. For further details, consult the Javadoc for Thebeanpostprocessor andordered interfaces. Also the note below onprogrammatic registration ofbeanpostprocessors

Note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.