Java Spring-bean

Source: Internet
Author: User

2017-11-06 18:59:30

    • Method of bean initialization and destruction

How to configure initialization and destruction:
* init-method= "Setup"
* destroy-method= "teardown"
When performing the destruction, the factory must be manually shut down and only valid for scope= "Singleton"(that is, the default value).

Configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"       Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">    <bean id=" Bean "class=" Spring3. Bean "init-method=" Setup "destroy-method=" teardown ">        <property name=" s "value=" Hello "/>    </bean ></beans>

Code files:

public class Bean {    private String s;    public void Sets (String s) {        THIS.S = s;    }    public void Setup () {        System.out.println ("This is the initialization method");    }    public void teardown () {        System.out.println ("This is the Destruction method");}    } public class Spring3 {    @Test public    void Demo1 () {        Classpathxmlapplicationcontext ac = new Classpathxmlapplicationcontext ("" +                "Config2.xml");        Bean B = (bean) Ac.getbean ("Bean");        Only Classpathxmlapplicationcontext has a close () method, ApplicationContext has no        ac.close ();    }}
    • Bean's life cycle

A single step in the life cycle of a bean:
1.instantiate Bean Object Instantiation
2.populate Properties Package Attributes
3. If the bean implements Beannameaware execution Setbeanname(let the current class understand the spring container)
4. If the bean implements Beanfactoryaware or Applicationcontextaware set the factory setbeanfactory or context objectSetapplicationcontext(Let the current class understand the spring container)
5. If there is a class implementation beanpostprocessor (pre-processing bean), execute postprocessbeforeinitialization
6. If the bean implements Initializingbean execution Afterpropertiesset
7. Call <bean init-method= "Init" > Specify initialization method init
8. If there is a class implementation beanpostprocessor (post-processing bean), execute postprocessafterinitialization
9. Perform business processing
10. If the bean implements Disposablebean execution destroy
11. Call <bean destroy-method= "Customerdestroy" > Specify the method of destruction Customerdestroy

Configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"       Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">    <bean id=" Bean "class=" Spring3. Bean "init-method=" Setup "destroy-method=" teardown ">        <property name=" s "value=" Hello "/>    </bean >    <!--post-processing beans do not need to add IDs and the system automatically calls-    <bean class= "Spring3. Mybeanpostprocessor "/></beans>

Code files:

Public interface B {public void Add ();} public class Bean implements b,disposablebean,beannameaware,applicationcontextaware,initializingbean{private String    S    Bean () {System.out.println ("First step: Default constructor Method");        } public void sets (String s) {System.out.println ("Second Step: Attribute injection");    THIS.S = s;        } public void Add () {System.out.println ("Nineth Step: Handling Business logic");    System.out.println ("This is the Add Method");    public void Setup () {System.out.println ("Step seventh: This is the initialization method");    } public void Teardown () {System.out.println ("This is the method of destruction");    } @Override public void Setbeanname (String s) {System.out.println ("Step three: ID number of the injected configuration" +s);        } @Override public void Setapplicationcontext (ApplicationContext applicationcontext) throws Beansexception {    System.out.println ("Fourth step: Injecting ApplicationContext" +applicationcontext);    } @Override public void Afterpropertiesset () throws Exception {System.out.println ("sixth step: Execute after property set"); } @Override public voidDestroy () throws Exception {System.out.println ("Tenth step: Spring Call Destruction Method"); }}

Custom beanpostprocessor

public class Mybeanpostprocessor implements Beanpostprocessor {    /**     * Bean: Instance Object     * Beanname: The identity of the class configured in the configuration file.     *    /public Object Postprocessbeforeinitialization (object bean, String beanname)            throws Beansexception {        System.out.println ("Fifth step: Execute before initialization ...");        return bean;    }    public Object Postprocessafterinitialization (Final object bean, String beanname)            throws beansexception {        System.out.println ("Eighth step: Execute after initialization ...");        return bean;    }}

Results:

    public void Demo1 () {        Classpathxmlapplicationcontext ac = new Classpathxmlapplicationcontext ("" +                "Config2.xml ");        Bean B = (bean) Ac.getbean ("Bean");        B.add ();        Only Classpathxmlapplicationcontext has a close () method, ApplicationContext has no        ac.close ();    } Output: First step: Default constructor Method Step two: Attribute injection step three: Inject configuration ID number Bean Fourth step: inject applicationcontextorg[email protected]6591f517:startup date [Mon-Nov 06 19:50:53 CST 2017]; Root of the context hierarchy Fifth step: Initialize before executing ... Sixth step: The property is set after the seventh step: This is the initialization method eighth step: Execute after initialization ... Nineth Step: Handling business logic This is the Add method tenth step: Spring Call destroy Method This is the Destroy method

Of course, the post-processing bean can be augmented with dynamic proxies.

However, it is important to note that this time when defining an object, you must use the interface as the type name, not the implementation class, because the proxy class is returned, the proxy class and the implementation class are peer relationships, and cannot be converted to each other.

Import Org.springframework.beans.beansexception;import Org.springframework.beans.factory.config.beanpostprocessor;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;public class Mybeanpostprocessor implements     beanpostprocessor {/** * Bean: Instance Object * Beanname: The identity of the class configured in the configuration file.        */Public object Postprocessbeforeinitialization (object bean, String beanname) throws Beansexception {        System.out.println ("Fifth step: Execute before initialization ...");    return bean;        The public object Postprocessafterinitialization (Final object bean, String beanname) throws Beansexception {        System.out.println ("Eighth step: Execute after initialization ..."); The dynamic proxy is enhanced with Object proxy = Proxy.newproxyinstance (Bean.getclass (). getClassLoader (), Bean.getclass (). Getinterfaces (), new Invocationhandler () {@Override public object Invoke (Object Pro      XY, method, object[] args) throws Throwable {                  System.out.println ("Permission check:");                        Object res = Method.invoke (bean, args);                    return res;        }                });    return proxy; }}public class Spring3 {@Test public void Demo1 () {Classpathxmlapplicationcontext AC = new Classpathxmlappli        Cationcontext ("" + "Config2.xml");        b b = (b) ac.getbean ("Bean");        B.add ();    Only Classpathxmlapplicationcontext has a close () method, ApplicationContext no Ac.close (); }} Results: First step: Default constructor Method Step two: Attribute injection step three: Inject configuration ID number Bean Fourth step: inject Applicationcontextorg[email protected]6591f517:startup date [ Mon Nov 20:18:39 CST 2017]; Root of the context hierarchy Fifth step: Initialize before executing ... Sixth step: The property is set after the seventh step: This is the initialization method eighth step: Execute after initialization ... Permission check: Nineth step: Handling business logic This is the Add method tenth step: Spring Call destroy Method This is the Destroy method

Java Spring-bean

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.