Spring bean definition & scope of Spring Bean

Spring bean definition

Table of contents

Spring bean definition

 

Spring configuration metadata

Spring Bean Scope

 

singleton scope:

 

Prototype scope:

Example:


 

Forming the backbone of the application are objects called beans managed by the Spring IoC container. Beans are instantiated, assembled, and objects managed by the Spring IoC container. These beans are provided by the container, for example, in the XML <bean/> definition, which we have seen in previous chapters is created in the form of configuration metadata.

The bean definition contains the following information called configuration metadata that the container needs to know:

  • How to create a bean

  • Bean life cycle details

  • Bean dependencies

All of the above configuration metadata is converted into a set of the following properties that make up each bean's definition.

Attributes describe
class This attribute is mandatory and specifies the bean class to be used to create the bean.
name This property specifies a unique bean identifier. When configuring XML-based metadata, you can specify bean identifiers using the id and/or name attributes
scope This property specifies a specific bean definition to create, which will be in the bean scope of the object discussed in this chapter.
constructor-arg This is used to inject dependencies and is discussed in the following sections.
properties This is used to inject dependencies and is discussed in the following sections.
autowiring mode This is used to inject dependencies and is discussed in the following sections.
lazy-initialization mode Lazy-initialized beans tell the IoC container to create the bean instance when it first asks for it, rather than at startup time.
initialization method The callback simply calls the container that has been set after all the necessary properties of the bean. It is discussed in the bean life cycle chapter.
destruction method The callback used when the containing bean container is destroyed. It is discussed in the bean life cycle chapter.

 

Spring configuration metadata

The Spring IoC container is completely decoupled from the format in which the configuration metadata is actually written. There are three important methods provided by the Spring container for configuring metadata:

  1. XML-based configuration file.

  2. Annotation-based configuration

  3. Java-based configuration

We have already seen how XML based configuration metadata is provided to the container, but let us see another example of different bean definitions including lazy initialization, initialization methods and destruction methods based on XML configuration files:

<?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-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id="..." class="..." lazy-init="true">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with initialization method -->
   <bean id="..." class="..." init-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id="..." class="..." destroy-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions go here -->

</beans>

 

Annotation-based configuration is discussed in a separate section. I deliberately keep it in a separate chapter because I hope to master some other important Spring concepts before starting to program with annotated dependency injection.

Spring Bean Scope

 

 

 

When defining a Spring <bean>, bean-scoped options must be declared. For example, to force Spring to generate a new bean instance, you should declare the bean's scope attribute as prototype. If you want Spring to return the same bean instance every time, you should declare the scope of the bean in the same way that a property is a singleton.

The Spring framework supports the following five scopes, three of which are only available when you use the web-aware ApplicationContext.

scope describe
singleton This scopes the bean definition to a single instance per Spring IoC container (default).
prototype This scopes a single bean definition to have any number of object instances.
request This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

This chapter will discuss the first two scopes and the remaining three will be discussed when we will discuss about Web-aware Spring ApplicationContext.

 

singleton scope:

If the scope is set to a singleton, the Spring IoC container creates only one instance of the object defined by that bean. This singleton is stored in the cache of such a singleton bean, and all subsequent requests and references against that bean return the cached object.

The default scope is always a singleton, but when you need an instance of the bean, you can set the scope attribute of the singleton in the bean configuration file, as shown below:

 

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
</bean>

Example:

Let's use the Eclipse IDE and follow the steps below to create a Spring application:

step describe
1 Create a project with a name SpringExample and create a package com.manongjc under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.manongjc package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

Here are the contents of the HelloWorld.java file:

package com.manongjc;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

The following is the content of the MainApp.java file:

​package com.manongjc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}​

The following is the beans.xml file that requires the singleton scope 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-3.0.xsd">

   <bean id="helloWorld" class="com.manongjc.HelloWorld" 
      scope="singleton">
   </bean>

</beans>​

Once creation of source code and bean configuration files is complete, run the application. If all goes well, this will print the following message:

​Your Message : I'm object A
Your Message : I'm object A​

Prototype scope:

If the scope is set to prototype, then the Spring IoC container creates a new bean instance of the object every time a request is made for that particular bean. As a rule, use prototype-scoped bean classes for all states and singleton-scoped beans for stateless beans.

To define a prototype scope, you can set the scope attribute for the prototype in the bean configuration file, as shown below:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="prototype">
    <!-- collaborators and configuration for this bean go here -->
</bean>

Example:

Let’s get the Eclipse IDE working in place and follow the steps below to create a Spring application:

step describe
1 Create a project with a name SpringExample and create a package com.manongjc under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.manongjc package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

Here are the contents of the HelloWorld.java file:

​package com.manongjc;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}​

The following is the content of the MainApp.java file:

​package com.manongjc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("I'm object A");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}​

The following is the required prototype-scoped configuration file beans.xml:

​<?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-3.0.xsd">

   <bean id="helloWorld" class="com.manongjc.HelloWorld" 
      scope="prototype">
   </bean>

</beans>​

创建源代码和bean配置文件完成后,让我们运行应用程序。如果一切顺利,这将打印以下信息:

​Your Message : I'm object A
Your Message : null​

 

 

Guess you like

Origin blog.csdn.net/2301_78835635/article/details/133553732