Spring IoC dependency injection beanfactory applicationcontext webapplicationcontext

Source: Internet
Author: User
Tags getcolor

I. Spring

Spring is a container that describes the dependency between classes through configuration files or annotations to automatically initialize classes and inject dependencies, it allows developers to quickly get out of the instantiation and dependency assembly of these underlying implementation classes and focus on more meaningful business logic development, at the same time, spring also implements code decoupling.

The injection method can be divided into three types: constructor injection, property injection, and interface injection. An additional interface needs to be declared through interface injection, which increases the number of classes and has no essential difference between its effect and attribute injection. Therefore, we do not advocate this method, spring supports constructor injection and property injection.

 

2. beanfactory

Beanfactory is the core interface of the Spring framework. It provides an advanced IOC configuration mechanism. applicationcontext is built on beanfactory and provides more application-oriented functions, it provides more application-oriented functions, and provides international support and framework practice systems, making it easier to create practical applications.

We generally call beanfactory as the IOC container and applicationcontext as the application context. But sometimes we call applicationcontext spring container for ease of writing.

For the purposes of the two, we can make a simple division: beanfactory is the infrastructure of the Spring framework, oriented to spring itself; applicationcontext is oriented to developers who use the Spring framework, in almost all application scenarios, we use applicationcontext instead of the underlying beanfactory.

We have a car class:

package spring.ioc.demo1;public class Car {    private String brand;    private String color;    private int maxSpeed;    public String getBrand() {        return brand;    }    public void setBrand(String brand) {        this.brand = brand;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }    public int getMaxSpeed() {        return maxSpeed;    }    public void setMaxSpeed(int maxSpeed) {        this.maxSpeed = maxSpeed;    }        public String toString(){        return "the car is:"+ getBrand() + ", color is:" +getColor() +", maxspeed is:"+getMaxSpeed();    }    public Car() {    }    public Car(String brand, String color, int maxSpeed) {        this.brand = brand;        this.color = color;        this.maxSpeed = maxSpeed;    }    public void introduce() {        System.out.println("brand:" + brand + ";color:" + color + ";maxSpeed:"                + maxSpeed);    }}

We configure the following in applicationcontext. xml:

<Bean id = "car1" class = "Spring. IOC. demo1.car "P: Brand =" Spring injection-Hongqi 001 "P: color =" Spring injection-purple "P: maxspeed =" 520 "/>

Use xmlbeanfactory to start the Spring IoC container:

public static void main(String[] args) {        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();        Resource res = resolver.getResource("classpath:applicationContext.xml");        BeanFactory factory = new XmlBeanFactory(res);
// Applicationcontext factory = new classpathxmlapplicationcontext ("applicationcontext. XML "); car = factory. getbean ("car1", car. class); system. out. println ("Car object initialization completed"); system. out. println (car. getmaxspeed ());}

1. xmlbeanfactory starts the IOC container by loading spring configuration information through resource, and then the bean can be obtained from the IOC container through factory. getbean.

2. When the IOC container is started through beanfactory, the bean defined in the configuration file is not initialized. The initialization action takes place in the first call.

3. for single-instance (Singleton) Beans, beanfactory caches bean instances. Therefore, when getbean is used for the second time, bean is directly obtained from the IOC container cache.

 

Iii. applicationcontext

If beanfactory is the heart of spring, applicationcontext is the complete body. applicationcontext is derived from beanfactory and provides more practical application-oriented functions. In beanfactory, many functions need to be implemented in the form of changes, while in applicationcontext, they can be implemented through configuration.

The main implementation classes of applicationcontext are classpathxmlapplicationcontext and filesystemxmlapplicationcontext. The former loads the configuration file from the class path by default, and the latter is installed in the configuration file from the file system by default.

Spring 3.0 supports configuration based on class annotations. The main function is from a sub-project named javaconfig of spring. Currently, javaconfig has been upgraded to a part of spring's core framework. A pojo labeled with @ configuration annotation can provide bean configuration information required by spring and XML-based configuration. Its advantage is that developers can easily control bean initialization.

Package spring. IOC. applicationcontext; import Org. springframework. context. annotation. bean; import Org. springframework. context. annotation. configuration; import spring. IOC. demo1.car; // indicates a configuration information provider class @ configurationpublic class beans {@ Bean (name = "car") // defines a bean public car buildcar () {car = new car (); car. setbrand ("Volvo"); car. setcolor ("black"); car. setmaxspeed (600); Return car ;}}

Spring provides a special applicationcontext implementation class for annotation-based configuration: annotationconfigapplicationcontext.

Public static void main (string [] ARGs) {// load bean configuration through a pojo with @ configuration to configure applicationcontext CTX = new annotationconfigapplicationcontext (beans. class); car = CTX. getbean ("car", car. class); system. out. println (CAR );}

A. classpathxmlapplicationcontext there are three ways to compile the path:

ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml"); ApplicationContext factory = new ClassPathXmlApplicationContext("file:E:/Workspaces/MyEclipse 8.5/Hello/src/applicationContext.xml");

B. The filesystemxmlapplicationcontext file system path has two relative and absolute paths.

ApplicationContext factory=new FileSystemXmlApplicationContext("src/applicationContext.xml");ApplicationContext factory=new FileSystemXmlApplicationContext("E:/Workspaces/MyEclipse 8.5/Hello/src/applicationContext.xml");

Applicationcontext delays loading. If a bean property is not injected, after beanfacotry is loaded, an exception will not be thrown until the getbean method is called for the first time. applicationcontext is a validation during initialization, this helps to check whether the dependent attributes are injected. Therefore, we usually choose applicationcontext.

The application context will pre-load all single-instance beans after the context is started. By pre-loading single-instance beans, make sure you don't have to wait when you need them because they have been created.

 

Iv. webapplicationcontext

Webapplicationcontext is specially designed for Web applications. It allows you to load the configuration file from the path of the relative web root directory to complete initialization. The reference of servletcontext can be obtained from webapplicationcontext, and the entire web application context object is placed in servletcontext, so that the Web application environment can access the spring application context.

The initialization method of webapplicationcontext is different from that of beanfactory and applicationcontext. Because webapplicationcontext requires a servletcontext instance, webapplicationcontext must have a Web Container before starting the instance, so as to avoid repeated loading of configuration files.

Implement the servletcontextaware interface and configure it in the configuration file. Spring will automatically inject servletcontext:

<! -- Automatically inject servletcontext through jspgetbean --> <bean id = "getservletcontext" class = "Spring. IOC. applicationcontext. jspgetbean"> </bean>
Package spring. IOC. applicationcontext; import javax. servlet. servletcontext; import Org. springframework. web. context. servletcontextaware; import Org. springframework. web. context. webapplicationcontext; import Org. springframework. web. context. support. webapplicationcontextutils; import spring. IOC. demo1.car; public class jspgetbean implements servletcontextaware {static public servletcontext; public static <t> T getbeanfromjsp (string beanname) {/* applicationcontext factory = new topology ("applicationcontext. XML ");
* Avoid repeatedly loading the configuration file and retrieve the bean directly from the context.
*/Webapplicationcontext factory = webapplicationcontextutils. getrequiredwebapplicationcontext (servletcontext); // You can also directly write this. getservletcontext object OBJ = factory. getbean (beanname, car. class); Return (t) OBJ ;}@ override public void setservletcontext (servletcontext arg0) {This. servletcontext = arg0 ;}}

The JSP page can directly obtain the beans in the IOC container through the above classes.

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ page language="java" import="spring.ioc.applicationContext.JspGetBean" %><%@ page language="java" import="spring.ioc.demo1.Car" %><%Car car = JspGetBean.getBeanFromJsp("car1");String temp = car.getBrand();%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Then, you can request a servlet to obtain bean information. The servlet code is as follows:

package spring.ioc.applicationContext;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import spring.ioc.demo1.Car;public class WebApplicationContextServlet extends HttpServlet {    /**     *      */    private static final long serialVersionUID = -5674896184804907736L;    public void doPost(HttpServletRequest req, HttpServletResponse res)            throws ServletException, IOException {        WebApplicationContext ctx = WebApplicationContextUtils                .getRequiredWebApplicationContext(this.getServletContext());        res.setCharacterEncoding("UTF-8");        Car car = ctx.getBean("car1",Car.class);        PrintWriter out = res.getWriter();        out.println(car);    }}

The preceding figure shows the usage of webapplicationcontext.

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.