[Spring Study Notes (2): Basic Bean Configuration]

I. Introduction

After learning Spring, I know that the Spring framework has two core functions: ①The Spring container is responsible for creating and managing all Java objects, but these Java objects are called Beans. ②The Spring container manages the dependencies between Beans in the container, and Spring uses a method called "dependency injection" to manage the dependencies between Beans. For developers like us, using the Spring framework mainly does two things: ① develop beans; ② configure beans. For the Spring framework, it is to create a Bean instance according to the configuration file, and call the method of the Bean instance to complete "dependency injection".

Second, the definition of Bean

A bean is an object instantiated, assembled and managed by the Spring IoC container.

2.1.1 Basic configuration of Bean (id and class)

<bean id = "  "  class = " "/>

Regarding the function and usage of the <bean> tag, as well as the role of the id and class attributes, we will explain in detail through a table.

category     describe
name bean
type Label
Affiliation beans tag
Function Defines objects managed by the Spring core container
Format

<beans>

        <bean />

        <bean></bean>

</beans>

Attributes

the list

Id: the id in the bean, using the container to obtain the corresponding bean through the id value, the value of the id in a container is unique, referred to as the unique identifier of the bean

Class: The type of bean, that is, the full path class name of the configured bean, specifying the specific implementation class of the bean.

example

<bean id = "bookDao" class = " com.system.dao.impl.BookDaoImpl" />

<bean id = "bookService" class = " com.system.service.impl.BookServiceImpl"></bean>

2.1.2 Special instructions:

Interfaces cannot be written in the Class attribute ! ! ! Because there is no way to create an object from an interface . Under normal circumstances, Spring will directly use the new keyword to create an instance of the Bean. Therefore, the class name of the bean implementation class must be provided in the class class.

2.1.3 Introductory case code implementation:

Requirements analysis: Hand over BookServiceImpl and BookDaoImpl to Spring management, and obtain the corresponding bean objects from the container for method invocation.

(1) Create a Maven project in IDEA

(2) Add Spring-dependent jar packages in pom.xml

(3) Create four classes BookService, BookServiceImpl, BookDao and BookDaoImpl

(4) Add the Spring configuration file in the resource folder to complete the Bean configuration

(5) Use the interface provided by Spring to complete the creation of the IOC container

(6) Get the object from the container to call the method

Step 1: Create a Maven project in IDEA

 Step 2: Add Spring-dependent jar packages in pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

 Step 3: Create four classes BookService, BookServiceImpl, BookDao and BookDaoImpl

 

 Step 4: Add the Spring configuration file in the resource folder to complete the Bean configuration

Add the Spring configuration file applicationContext.xml under resources, and complete the Bean configuration

Step 5: Complete the bean configuration in the 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标签标示配置bean
    	id属性标示给bean起名字
    	class属性表示给bean定义类型
	-->
    <bean id="bookDao" class="com.system.dao.impl.BookDaoImpl"/>
    <bean id="bookService" class="com.system.service.impl.BookServiceImpl"/>

</beans>

Step 6: Get the IOC container

Use the interface provided by Spring to complete the creation of the IOC container, create the App class, and write the main method

public class App {
    public static void main(String[] args) {
        //获取IOC容器
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 
    }
}

Step 7: Get the object from the container to make a method call

public class APP2 {
    public static void main(String[] args) {
        //3.获取IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //4.获取bean
       //BookDao bookDao =(BookDao) ctx.getBean("bookDao");
       //bookDao.save();
       BookService bookService = (BookService) ctx.getBean("bookService");
       bookService.save();
    }
}

Step 8: Run the program

The test results are:

 2.2 name attribute in Bean

category describe
name

name

type Attributes
Affiliation bean tag
Function Define the alias of the bean, multiple can be defined, separated by comma (,) semicolon (;) space ( )
example

<bean id = "bookDao"  name = " dao bookDaoImpl" class = " com.system.dao.impl.BookDaoImpl" />

<bean name = "service,bookServiceImpl" class = " com.system.service.impl.BookServiceImpl">

</bean>

2.2.1 Instructions for use

Step 1: Configure Aliases

Open the Spring configuration file applicationContext.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.xsd">

    <!--name:为bean指定别名,别名可以有多个,使用逗号,分号,空格进行分隔-->
    <bean id="bookService" name="service service4 bookEbi" class="com.system.service.impl.BookServiceImpl">
        <property name="bookDao" ref="bookDao"/>
    </bean>

    <!--scope:为bean设置作用范围,可选值为单例singloton,非单例prototype-->
    <bean id="bookDao" name="dao" class="com.system.dao.impl.BookDaoImpl"/>
</beans>

Note: The full name of Ebi is Enterprise Business Interface, translated as Enterprise Business Interface

Step 2: Get the bean object according to the name container

public class AppForName {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //此处根据bean标签的id属性和name属性的任意一个值来获取bean对象
        BookService bookService = (BookService) ctx.getBean("service4");
        bookService.save();
    }
}

Step 3: Run the program 

2.3 scope configuration in Bean

The scope of the Bean is an important content of the Bean property configuration

First look at the configuration properties of the Bean scope through the table:

category describe
name scope
type Attributes
Affiliation bean tag
Function

Define the scope of the bean, the optional scope is as follows

(1) singleton: singleton (default)

(2) prototype: non-singleton

example <bean id = "bookDao" class = "com.system.dao.impl.BookDaoImpl" scope = "prototype"/>

2.3.1  Verify whether the object in the IOC container is a singleton

Verification ideas:

Get the same bean twice, print the object to the console, and check whether the printed address values ​​are consistent.

Implementation:

Create an AppForScope class and verify it in its main method.

public class AppForScope {
    public static void main(String[] args) {
        ApplicationContext ctx = new
                ClassPathXmlApplicationContext("applicationContext.xml");

        BookDao bookDao1 = (BookDao) ctx.getBean("bookDao");
        BookDao bookDao2 = (BookDao) ctx.getBean("bookDao");
        System.out.println(bookDao1);
        System.out.println(bookDao2);
    }
}

Print, observe the print results of the console:

 in conclusion:

The bean objects created by Spring are all singletons

2.3.2 Configure beans as non-singleton 

(1)在Spring配置文件中,配置scope属性来实现bean的非单例创建

(2)在Spring的配置文件中,修改<bean>的scope属性

<bean id="bookDao" name="dao" class="com.system.dao.impl.BookDaoImpl" scope=""/>

(3)将scope设置为singleton

<bean id="bookDao" name="dao" class="com.system.dao.impl.BookDaoImpl" scope="singleton"/>

运行AppForScope,打印看结果

(4)将scope设置为prototype

<bean id="bookDao" name="dao" class="com.system.dao.impl.BookDaoImpl" scope="prototype"/>

运行AppForScope,打印看结果

结论:使用bean的scope属性可以控制bean的创建是否为单例:

  • singleton默认为单例

  • prototype为非单例

 2.4Bean基础配置小结

关于Bean的基础配置中,需要掌握以下属性

<bean

        id="bean的唯一标识"

        class="bean的类全名"

        scope="bean的作用范围,有singleton(默认)和prototype"

        name="为bean取的别名"/>

Guess you like

Origin blog.csdn.net/long_0901/article/details/124718273