"Step-by-step learning Spring" Spring bean management (top)

Source: Internet
Author: User

1. Spring Factory class

The Spring factory class we used in the demo in front of us is classpathxmlapplicationcontext, and we can see that he has a brother class Filesystemapplicationcontext, This class is the same as loading a configuration file under a non-classpath path.

From the inheritance graph, you can see the applicationcontext that we often see, which is the factory class interface introduced in the new version. In the old version is Beanfactory, is in the old version based on the addition of several new features, such as internationalization, Resourceloader and so on. There is also a difference between the time when the bean is loaded, the beanfactory is created when the bean is used, and the ApplicationContext is created when the configuration file is loaded with all non-lazy-loaded singleton cases.

@Test/*** 使用beanFactory加载bean*/public void demo3() {    // 老方式的工厂类,需要自己创建Resource对象进行加载。    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("application-context.xml"));    // 通过工厂获取类对象    UserService userService = (UserService) beanFactory.getBean("userService");    userService.sayHello();}
2. Spring Bean Management 2.1 Three ways to instantiate beans
    • Instantiating using the class constructor (default no parameters)
    • Instantiating using a static factory method (Simple Factory mode)
    • Using instance Factory mode instantiation (Factory method mode)

The general situation is in the first way, only the structure of the class is very complex in the case of the two behind.

2.1.1 Instantiating using class constructors
    • Bean
package com.ioc.demo2;/** * Bean实例化的三种方式:采用无参的构造方法的方式 */public class Bean1 {    public Bean1() {        System.out.println("Bean1 被实例化了。");    }}
    • Xml
<!-- 无参数构造方法构建 --><bean id="bean1" class="com.ioc.demo2.Bean1"></bean>
    • Call
@Testpublic void demo1() {    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");    Bean1 bean = (Bean1) applicationContext.getBean("bean1");}
2.1.2 Static Factory method instantiation
    • Bean
/** * Bean的实例化三种方式:静态工厂实例化方式 */public class Bean2 {}
    • Beanfactory
/** * Bean2的静态工厂 */public class Bean2Factory {        public static Bean2 createBean2() {        System.out.println("Bean2Factory 执行了。");        return new Bean2();    }}
    • Xml
<!-- 静态工厂的方式 --><bean id="bean2" class="com.ioc.demo2.Bean2Factory" factory-method="createBean2"></bean>
    • Call
@Testpublic void demo2() {    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");    Bean2 bean = (Bean2) applicationContext.getBean("bean2");}
2.1.3 Using instance Factory mode instantiation
    • Bean
/** * 使用实例工厂模式实例化 */public class Bean3 {}
    • Beanfactory
/** * Bean3的实例工厂 */public class Bean3Factory {    public Bean3 createBean3() {        System.out.println("Bean3Factory 被调用了。");        return new Bean3();    }}
    • Xml
<!-- 实例工厂的方式 --><bean id="bean3Factory" class="com.ioc.demo2.Bean3Factory"></bean><bean id="bean3" factory-bean="bean3Factory" factory-method="createBean3"></bean>
    • Call
@Testpublic void demo3() {    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");    Bean3 bean = (Bean3) applicationContext.getBean("bean3");}
2.2 Bean's common configuration 2.2.1 ID and name
    • In general, when you assemble a bean, you specify an ID property as the name of the bean
    • The id attribute is unique within the IOC container
    • Name is also unique, the difference between the same ID is that there can be special characters. This should be a historical reason, not to repeat.
2.2.2 Class
    • Sets the name of the full path of a class, with the main role being an instance of the IOC container generation class
2.2.3 Scope
category Description
Singleton (default) Only one bean instance exists in the SPRINGIOC container, and the bean exists as a single instance
Prototype A new instance is returned each time Getbean () is called
Request Each HTTP request creates a new bean that applies only to the WEBAPPLICATIONCONTEXT environment
Session The same HTTP session shares a bean, and different HTTP sessions use different beans. This scope applies only to Webapplicationcontext environments
2.3 The Bean life cycle in the spring container

Spring initializes the bean or destroys the bean, and sometimes it needs to do some work, so spring can invoke the bean's declaration-period method when it creates and destroys the bean.

<bean id="xxx" class="...Yoo" init-method="init" destory-method="destory" />

Init is called when the bean is loaded into the container, and destroy is called when the bean is removed from the container (Scope=singleton valid)

2.3.1 Instantiate Bean Object instantiation

That is, the constructor method of the calling class.

2.3.2 Populate Properties Package property

The property setting method that invokes the class.

2.3.3 If the bean implements Beannameaware, the Setbeanname is executed

This is called when the Bean is set to name, which can be imagined as the container as Map,name is the key.

2.3.4 If the bean implements Beanfactoryaware or Applicationcontextaware sets the factory, the Setbeanfactory or context object is executed Setapplicationcontext

Called when a container is set for the bean.

2.3.5 If there is a class implementation beanpostprocessor (post-processing bean), execute postprocessbeforeinitialization

Called before the Init-method is called.

2.3.6 if the bean implements Initializingbean, the afterpropertiesset is enforced.

Called after the property is set.

2.3.7 Call <bean init-method="init">The specified initialization method

Executes the Init method.

2.3.8 If there is a class implementation beanpostprocessor (post-processing bean), execute postprocessafterinitialization

Called after the Init-method is called.

2.3.9 Performing Business Processing

Called the business method in the bean.

2.3.10 if the bean implements Disposablebean, the Destory method is executed

The method of destruction in spring itself.

2.3.11 Call <bean destory-method="teardown">Specified method of Destruction

Executes the teardown method.

2.3.12 Related Codes
    • Bean
Package Com.ioc.demo3;import Org.springframework.beans.beansexception;import Org.springframework.beans.factory.beannameaware;import Org.springframework.beans.factory.disposablebean;import Org.springframework.beans.factory.initializingbean;import Org.springframework.context.applicationcontext;import Org.springframework.context.applicationcontextaware;public class Bean implements Beannameaware,    Applicationcontextaware, Initializingbean, disposablebean{private String name;    Public Bean () {System.out.println ("First step: Construct method");        public void SetName (String name) {System.out.println ("Step Two: Set properties");    THIS.name = name;    } public void Setbeanname (String name) {System.out.println ("step three: Set the name of the Bean:" + name); } public void Setapplicationcontext (ApplicationContext applicationcontext) throws Beansexception {SYSTEM.OUT.PR    Intln ("Fourth step: Setting up the Bean Factory");    } public void Afterpropertiesset () throws Exception {System.out.println ("sixth step: After property set"); } public void init () {System.out.println ("Seventh Step: Initialize Method");    public void Run () {System.out.println ("nineth Step: Business code");    } public void Destroy () throws Exception {System.out.println ("Tenth step: Spring's own destruction");    } public void Teardown () {System.out.println ("11th Step: Destruction Method"); }}
    • Mybeanpostprocessor
package com.ioc.demo3;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {    // 可以用beanName对要生效的bean做过滤操作    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {        System.out.println("第四步:bean初始化前");        return bean;    }    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {        System.out.println("第八步:bean初始化后方法");        return bean;    }}
    • Xml
<!-- Bean的声明周期============================================ --><bean id="bean" class="com.ioc.demo3.Bean" init-method="init" destroy-method="teardown">    <property name="name" value="xxx"></property></bean><!-- 注意这个配置是对所有的bean都生效的 --><bean class="com.ioc.demo3.MyBeanPostProcessor"></bean>
    • Call
package com.ioc.demo3;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringDemo3 {        @Test    public void demo1() {        // ApplicationContext接口没有close方法,故直接使用了其实现类        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");        Bean bean = (Bean)context.getBean("bean");        bean.run();        context.close();    }}
    • Execution results
第一步:构造方法第二步:设置属性第三步:设置bean的名称:bean第四步:设置bean工厂第四步:bean初始化前第六步:属性设置后第七步:初始化方法第八步:bean初始化后方法第九步:业务代码第十步:spring自身的销毁第十一步:销毁方法
2.3.13 methods in the Beanpostprocessor enhancement class using the Declaration cycle

This essentially enables dynamic proxies for the methods in the class, paving the way for the AOP behind.

Below is a chestnut: Add a function of authentication to the Delete method without changing the specific class method .

    • Interface class
package com.ioc.demo3;public interface BeanDao {        public void find();    public void add();    public void delete();    public void update();}
    • Interface Implementation Class
package com.ioc.demo3;public class BeanDaoImpl implements BeanDao {    public void find() {        System.out.println("查询");    }    public void add() {        System.out.println("添加");    }    public void delete() {        System.out.println("删除");    }    public void update() {        System.out.println("更新");    }}
    • beanpostprocessor
Package Com.ioc.demo3;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;import Org.springframework.beans.beansexception;import Org.springframework.beans.factory.config.beanpostprocessor;public class Mybeanpostprocessor Implements Beanpostprocessor {public Object Postprocessbeforeinitialization (final Object Bean, String beanname) throws Beansexcep        tion {System.out.println ("Fourth step: Before Bean initialization");    return bean; public Object Postprocessafterinitialization (final Object Bean, String beanname) throws Beansexception {Syste        M.out.println ("Eighth step: Method after Bean initialization"); if (Beanname.equals ("Beandao")) {Object proxy = proxy.newproxyinstance (Bean.getclass (). getClassLoader (), Bean. GetClass (). Getinterfaces (), new Invocationhandler () {public Object invoke (Object proxy, Me       Thod method, object[] args) throws Throwable {if (Method.getname () equals ("delete")) {                 SYSTEM.OUT.PRINTLN ("Authentication is the root user");                    Return Method.invoke (bean, args);                } return Method.invoke (bean, args);            }            });        return proxy;    } return bean; }}
    • Xml
<bean class="com.ioc.demo3.MyBeanPostProcessor"></bean><bean id="beanDao" class="com.ioc.demo3.BeanDaoImpl"></bean>
    • Call
package com.ioc.demo3;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringDemo3 {        @Test    public void demo1() {        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");        BeanDao beanDao = (BeanDao)context.getBean("beanDao");        beanDao.add();        beanDao.delete();        beanDao.find();        beanDao.update();    }}

"Step-by-step learning Spring" Spring bean management (top)

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.