Spring-----4, using the spring container

Source: Internet
Author: User
Tags event listener getmessage gettext

Spring has two core interfaces:beanfactory and applicationcontext(beanfactory sub-interfaces); they all represent spring containers, The spring container is the factory that generates the bean instances, and the Bean;bean in the Management container is the basic unit of spring management, in the spring-based Java EE application, all the components are treated as beans, including the data source, Hibernate's Sesisonfactoy, transaction manager, etc.

All components in the application are managed by spring, which is managed by the bean, and spring is responsible for creating the bean instance and managing its lifecycle

The spring container is responsible for creating the bean instance, so you need to know the implementation class for each bean, and the Java program is interface-oriented, without concern for the implementation class of the bean instance, but the spring container must be able to know exactly what the implementation class is for each bean instance. Therefore, the spring configuration file must precisely configure the implementation class of the Bean instance

First, Spring container

The most basic interface of spring container is beanfactory: it is responsible for configuring, creating, managing bean, managing the dependency between Bean and Bean, its implementing class has xmlbeanfactory, and its subclass ApplicationContext implementation class has classpathxmlapplicationcontext,filesystemxmlapplicationcontext, Annotationconfigapplicationcontext; Using spring containers in Web applications, usually with Xmlwebapplicationcontext, Annotationconfigapplicationcontext

When you create a spring container instance, you must provide the bean detailed configuration information that is managed by the spring container. When you create an Beanfactory instance, you provide an XML configuration file as a parameter. XML configuration files typically use the resource object to pass in

Beanfactory Interface Common methods:

Boolean Containsbean (String Beanid): Determines whether the spring container contains a bean instance with ID Beanid

<T> T Getbean (class<t> requiredtype): Gets the unique bean instance of the spring container that belongs to the Requiredtype type

Obejct Getbean (String Beanid): Returns a bean instance with a container ID of Beanid

<T> T Getbean (String beanid,class<t> requiredtype): Returns a bean with a container ID of Beanid and a type of requiredtype

Class<?> GetType (String Beanid): Returns the type of the specified bean instance in the container

For stand-alone applications, you can instantiate the beanfactory://search under the current file path by using the following method to create a resource object Inputstreamresource ISR = new Beans.xml file Filesystemresource ("Bean.xml");//To create a beanfactory instance xmlbeanfactory factory = new Xmlbeanfactory (ISR) with the resource object as a parameter; The search class loads the path, creates the resource object in the Beans.xml file under the class load path classpathresource res = new Classpathresource ("Beans.xml");// Create Beanfactory instance Xmlbeanfactory factory = new Xmlbeanfactory (res) with resource object as parameter;

There are multiple attribute profiles in the app, You should use the Beanfcatory subinterface ApplicationContext to create instances of beanfactory ApplicationContext Common implementation classes: Filesystemxmlapplicationcontext: File system-based XML provisioning ApplicationContext instance Classpathxmlapplicationcontext: Creating an ApplicationContext instance with an XML configuration file under a class load path requires loading multiple XML configuration files at the same time. Can be used as follows://Search Classpath path, to Classpath path under the Bean.xml, service.xml file creation Applicationcontextapplicationcontext AppContext = New Classpathxmlapplicationcontext (New string[]{"Bean.xml", "Service.xml"}), or//to bean.xml under the specified path, Service.xml file creation Applicationcontextapplicationcontext AppContext = new Filesystemxmlapplicationcontext (New String[]{" Bean.xml "," Service.xml "});

The spring configuration file can be used to define the semantic constraints of the configuration file using the XML Schema, or the DTD (cannot use spring2.x, Spring3.0 new configuration tag) <?xml version= "1.0" encoding= "UTF-8"? ><!--using spring-beans-3.0.xsd semantic constraints--><beans xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"    xmlns= "Http://www.springframework.org/schema/beans"    xsi:schemalocation= "http://www.springframework.org/ Schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> ..... </beans". ......   > <?xml version= "1.0" encoding= "UTF-8"?><!--specify DTD information for spring configuration files--><! DOCTYPE beans Public "-//spring//dtd BEAN 2.0//en" "Http://www.springframework.org/dtd/spring-beans-2.0.dtd" >< Beans>   ...</beans>


Second, the use of ApplicationContext

Application allows the container to be manipulated declaratively, without having to create it manually, and with support classes such as Contextloader, which are automatically created when the Web app starts Applicaioncontext ; You can also create ApplicationContext programmatically

In addition to providing all the features supported by Beanfactory, ApplicationContext has the following additional features:

Inherits the Messagesource interface, thus providing international support

Resource access, such as URLs and files

Event mechanism

Loading multiple configuration files

Start with a declarative, and create a spring container

When the system creates a ApplicationContext container, all singleton beans are pre-initialized by default, that is, when the ApplicationContext container is initialized, all singleton beans in the container are instantiated

Third, the international support of ApplicationContext

Methods for internationalization in the Messagesource interface:

String getMessage (stringcode,object[] Args,locale Loc)

String getMessage (stringcode,object[] Args,stringdefault,locale Loc)

String getMessage (Messagesourceresolvableresolvable,locale Locale)

ApplicationContext is the three way to accomplish internationalization, when the program creates the ApplicationContext container, Spring automatically finds the bean instance named Messagesource in the configuration file, Once the bean instance is found, the call to the above 3 methods is delegated to the Messagesource bean, and if no bean,applicationcontext finds the Messagesourcebean in its parent definition; It is used as messagesource;

If the Messagesource Bean cannot be found, the system will create an empty staticmessagesourcebean that can accept the call of the above three methods;

The Resourcebundlemessagesource class is typically used when configuring Messagesource beans in Spring

<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBundleMessageSource" >          < Property name= "Basenames" >              <list>                  <value>message</value>                  <!--If there are multiple resource files, All listed here-              </list>          </property></bean>

American English resource file (message_en_us.properties) Hello=welcome,{0}now=now is:{0}

Simplified Chinese resource file (message.properties) hellow= Welcome, {0}now= Now time is: {0} because the resource file contains non-Western European text, you should use the Native2ascii tool (available in the bin directory of the JDK) Internationalize This resource file: Place the file in the JDK's Bin directory and enter the command native2ascii message.properties message_zh_cn.properties


public class Springtest {public      static void Main (string[] args) {           ApplicationContext ctx = new Classpathxmlapplic Ationcontext ("Applicationcontext.xml");           Create array           string[] A = {"Reader"};           Use the GetMessage method to obtain localization information; The Getdefault method of the Locale           String hello = ctx.getmessage ("Hello", A, Locale.getdefault ());           Object[] B = {new Date ()};           String now = Ctx.getmessage ("Now", B, Locale.getdefault ());           Print out two localized messages           System.out.println (hello);           System.out.println (now);      }}



Iv. the event mechanism of ApplicationContext

The mechanism of ApplicationContext is the realization of the observer design pattern, through the Applicationevent class and the Applicationlistener interface, can realize applicationcontext thing processing If there is a applictionlistenerbean in the container, the Applicationlistener bean will be automatically triggered whenever Applicaitoncontext publishes Applicationevent.

The Spring event framework has the following two key members:

Applicationevent: Container event, must be published by ApplicationContext

Applicationlistener: Listener, which can be held by any listener bean in the container

In fact, spring's event mechanism is basically similar to all event mechanisms that require event sources, events, and event listeners, except that the event source here is ApplicationContext and the event must be triggered by a Java program display

/** * Defines a applicationevent class whose object is a spring container event * */public class EmailEvent extends Applicationevent {      private String a ddress;      private String text;       Public emailevent (Object source) {           super (source);      }       Defines a parameterized constructor public      emailevent (Object source, string address, string text) {           super (source);           this.address = address;           This.text = text;      }       Public String getaddress () {           return address;      }       public void setaddress (String address) {           this.address = address;      }       Public String GetText () {           return text;      }       public void SetText (String text) {           this.text = text;      }}

/** * Container Listener Class */public class Emailnotifier implements Applicationlistener {       /**       * This method is triggered whenever any event occurs within a container */      @Override public      void Onapplicationevent (Applicationevent evt) {           if (evt instanceof emailevent) {                 // Only handle emailevent, send email notification ...                 emailevent emailevent = (emailevent) evt;                 System.out.println ("Accept address to send mail" + emailevent.getaddress ());                 SYSTEM.OUT.PRINTLN ("message body to send mail" + emailevent.gettext ());           } else {                 //container built-in events do not make any processing                 System.out.println ("event of the container itself:" + evt);}           }      

<beans>      <!--configuration Listener--      <bean class= "Org.app.main.EmailNotifier"/></beans> <!-- When you configure a bean,spring container that implements Applicationlistener in spring, it treats the bean as the listener for the container event--><!--When the system creates the spring container, Container events are automatically triggered when the spring container is loaded, and container event listeners can listen to these events--><!--in addition, the program can invoke the Applicationcontect pulishevent () method to proactively trigger container events--

/** * Program calls ApplicationContext Publishevent to trigger event * */public class Springtest {public       static void Main (string[] args) { C3/>applicationcontext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");           Create a Applicationevent object           emailevent ele = new EmailEvent ("Hello", "[email protected]", "This is a Test");           Active Trigger Container Event           ctx.publishevent (ele);}      }

Operation Result:

Event for container itself: org.springframework.context.event.contextrefreshedevent[source=org[email protected]2d776d65:startup Date [Fri 14:48:01 gmt+08:00 2014]; Root of context hierarchy]

Accept address to send mail [email protected]

The body of the message that needs to be sent the message is a test

It can be seen from the execution result that the listener not only monitors the events triggered by the program, but also hears the events built into the container; in fact, if the developer needs to callback the custom method when the spring container is initialized and destroyed, it can be implemented by the above event listener.

If the Bean wants to publish an event, the bean must obtain a reference to its container, and if the program does not directly get a reference to the container, then the bean should implement the Applicationcontextaware or Beanfactoryaware interface so that the container's reference can be obtained



Spring provides several built-in events:

Contextrefreshedevent:applicationcontext container initialization or refresh triggers the event; The initialization here means that all beans are loaded successfully, the post-processing bean is detected and activated, and all singleton beans are pre-instantiated. ApplicationContext container is ready for use

Contextstartedevent: When using the Configurableapplicationcontext (ApplicationContext sub-Interface) interface of the start () The event is triggered when the ApplicationContext container is started by the method, and the bean instance of the container management life cycle gets a specified start signal, which is common when restarting after a stop is often required

Contextclosedevent: When using the Configurableapplicationcontext (ApplicationContext sub-Interface) interface, close () The event is triggered when the ApplicationContext container is closed by the

Contextstoppedevent: Stop () when using the Configurableapplicationcontext (ApplicationContext sub-Interface) interface The event is triggered when the ApplicationContext container is stopped, and "stop" here means that the bean instance of the container management life cycle will get a specified stop signal, and the stopped spring container can call the start () method again to restart

Requesthandledevent:web related events that can only be applied with web apps that use Dispatcherservlet; when you use spring as the front-end MVC controller, the event is automatically triggered when spring processes user requests.

V. Let the bean get the spring container

Some of the examples described above are that the program first creates the spring container and then calls the Spring container's Getbean () method to get the beans in the spring container, in which case the program always holds a reference to the spring container

But in real-world applications, especially in Web applications, the spring container is typically configured in a declarative manner: Configuring a listener in the. xml file, the listener will be responsible for initializing the spring container, and the front-end MVC framework can call the spring container directly ( No need to access the spring container itself); In this case, the bean in the container is under container management without having to actively access the container, just accept the container's injection management; the dependency of the bean instance is typically injected dynamically by the container, without the need for the Bean instance to actively request

In this case, the bean in the spring container usually does not need to access the other beans in the container-----take dependency injection, let spring inject the dependent bean into the dependent bean, but in some special cases, The bean in the container may need to proactively access the spring container itself, and spring is ready for that requirement.

The bean that implements the Beanfactoryaware interface has the ability to access the Beanfactory container, and after the bean instance that implements the Beanfactoryaware (/applicationcontextaware) interface is created by the container, He will have a reference that points to the Beanfactory;beanfactoryaware interface that created it only Setbeanfactory (beanfactorybeanfactory) (/ Setapplicationcontext (Applicationcontextappicationcontext)) method: The Beanfactory in this method points to the beanfactory that created it, which is called by spring When the spring container calls the method, it passes itself as a parameter to the method

/** * Defines the Bean class, implements the Applicationcontextaware interface, and the class will have the ability to access the container * */public class Chinese implements Applicationcontextaware {      //Beanfactory container is saved with member variables      private ApplicationContext ctx;       /**       * Method required to implement the Applicationcontextaware interface       *      /@Override public      void Setapplicationcontext ( ApplicationContext ctx) throws Beansexception {           this.ctx = CTX;      }       Get Applicaitoncontext test method public      ApplicationContext GetContext () {           return ctx;      }}


Implementing the Applicationcontextaware interface allows the bean to have the ability to access the container, but it pollutes the code and causes the code to be coupled with the spring interface, so if it is not particularly necessary, do not directly access the container








Spring-----4, using the spring container

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.