SSM framework--Spring configuration file

Spring configuration file

1. Basic configuration of the Bean tag

insert image description here
The configuration object is handed over to Spring to create.
By default, it invokes the no-argument constructor in the class . If there is no no-argument constructor, it cannot be created successfully.

Basic properties:

  • id : The role is to uniquely identify, that is to say, within the configuration file, duplication is not allowed
  • class : the fully qualified class name of the bean

2. Range configuration of the Bean tag

scope: refers to the scope of the object, the values ​​are as follows:
insert image description here

Test the difference between singleton and prototype:

The first case:
In the Spring configuration file applicationContext.xml, add scope after the class as singleton:

insert image description here

In order to facilitate testing, create a package "com.xy.test" under the test file
to create a test class, "SpringTest":

insert image description here

Add coordinates in the pom.xml file, the code is as follows:

 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

Premise: You need to download the IDEA plug-in junit
IDEA plug-in installation method : Search and install the JunitGenerator V2.0 plug-in
Junit jar package download
and configure the Junit test environment

insert image description here

Write the test method, the code is as follows:

public class SpringTest {
    
    
    @Test
//    测试scope属性
    public void test1(){
    
    
//        获取客户端代码
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
//        调动getBean方法
        UserDao userDao1 = (UserDao) app.getBean("userDao");
        UserDao userDao2 = (UserDao) app.getBean("userDao");
        System.out.println(userDao1);
        System.out.println(userDao2);
    }
}

Running result: the two addresses are the same, indicating that there is a Bean of userDao in the Spring container

insert image description here

The second case:
In the Spring configuration file applicationContext.xml, add scope as prototype after class:

insert image description here

The running results are inconsistent, indicating that there are multiple userDao in the Spring container

The creation timing of the test object Bean: the
creation timing of the Bean is different because the scope is configured as a singleton and the prototype is different

The first case (singleton):
in applicationContext.xml:

<bean id="userDao" class="com.xy.dao.impl.UserDaoImpl" scope="singleton"></bean>

By default, the above configuration means that the object is created with no-argument construction, so it is necessary to override its no-argument construction inside UserDaoImpl:

//    无参构造,快捷键fn+ctrl+insert
    public UserDaoImpl() {
    
    
        System.out.println("UserDaoImpl创建...");
    }

This sentence is executed once, and the console is printed once, which proves that the method with no parameters is called once, and the construction with no parameters is called once, which means that the object is created once.

insert image description here

Put a breakpoint before the first line of code in the test class:

insert image description here

Click the green icon above the breakpoint and select "Debug":

insert image description here

Click "Next" to jump in and execute step by step:

insert image description here

As a result of running, the UserDaoImpl is created, but the object is not obtained:

insert image description here

Running results of multiple single-step executions:

insert image description here

Indicates when the Bean is created when the configuration file is loaded to create the Spring container

The second case (prototype):
in applicationContext.xml:

<bean id="userDao" class="com.xy.dao.impl.UserDaoImpl" scope="prototype"></bean>

The operation is the same as above:

Click a single step to create a Spring configuration file, but the Bean object is not created

insert image description here

Click again to execute, indicating that the Bean has been created

insert image description here

Press it again, and print another line,
indicating that the Bean object has created another

insert image description here

This shows that the time to create a Bean in Prototype is to create a Bean every time you getBean

Summarize:
insert image description here

3. Bean life cycle configuration

  • init-method: the name of the initialization method in the specified class
  • destroy-method: the name of the destruction method in the specified class

Create an initialization method and a destruction method in UserDaoImpl:

//    对象创建完毕后的初始化方法
    public void init(){
    
    
        System.out.println("初始化方法...");
    }

    //    对象销毁之前的销毁方法
    public void destroy() {
    
    
        System.out.println("销毁方法...");
    }

Configure the two properties init-method and destroy-method in the applicationContext configuration file:

    <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl" init-method="init" destroy-method="destroy" ></bean>

Manually close the Spring container in the test class so that the code can execute the destruction method in time

    public void test1() {
    
    
//        获取客户端代码
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//        调动getBean方法
        UserDao userDao1 = (UserDao) app.getBean("userDao");
        System.out.println(userDao1);
        app.close();

    }

operation result:

insert image description here

4. Bean instantiation in three ways

  • No-argument constructor instantiation (the most commonly used, has been used above)
  • Factory static method instantiation
  • Factory instance method instantiation

Factory static method instantiation:

Create a new class, a static factory class:
insert image description here

Write a static method in a static method class:

package com.xy.factory;

import com.xy.dao.UserDao;
import com.xy.dao.impl.UserDaoImpl;

public class StaticFactory {
    
    
    public static UserDao  getUserDao(){
    
    
        return new UserDaoImpl();
    }
}

Change the class of the configuration file to a static factory:
select the static factory, right-click to copy the fully qualified name,
replace the class attribute of the configuration file with
class, and then add a factory-method attribute to specify the factory method in the static factory

insert image description here

    <bean id="userDao" class="com.xy.factory.StaticFactory" factory-method="getUserDao" ></bean>

The test method does not need to be changed, comment out the close, and the running result is:

insert image description here
Factory instance method instantiation:

Create an instance factory inside the factory file:

insert image description here

Create method in instance method:

package com.xy.factory;

import com.xy.dao.UserDao;
import com.xy.dao.impl.UserDaoImpl;

public class DynamicFactory {
    
    
        public  UserDao getUserDao(){
    
    
            return new UserDaoImpl();
        }
    
}

In the configuration file, you need to first generate the factory object Spring container, and then adjust the internal method of the factory:

    <bean id="factory" class="com.xy.factory.DynamicFactory" ></bean>
    <bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>

operation result:

insert image description here

5. Bean dependency injection analysis

Create a service interface:

insert image description here

Simply write a method in the interface:

public interface UserService {
    
    
    public void save();
}

Create an interface implementation:

insert image description here

Implement the interface method:

public class UserServiceImpl implements UserService {
    
    

    public void save() {
    
    
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) app.getBean("userDao");
        userDao.save();
    }
}

Create a test that acts as the web layer:
insert image description here
write a main method:

public class UserController {
    
    
    public static void main(String[] args) {
    
    
        UserService userService=new UserServiceImpl();
        userService.save();
    }
}

operation result:

insert image description here

Configure in the configuration file:

    <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl"  ></bean>
    <bean id="userService" class="com.xy.service.impl.UserServiceImpl"></bean>

Let the Spring container generate:
delete the original in UserController and rewrite the code

public class UserController {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }
}

After setting up the environment, the running result:

insert image description here

There are certain problems in the environment built above:
insert image description here
modify the idea:
insert image description here
and there are two ways to inject UserDao into UserService inside the Spring container: with parameter construction and set method

6. Bean dependency injection concept

Dependency Injection (Dependency Injection): It is the specific implementation of the core IOC of the Spring framework.

Dao is required in Service, that is, Service requires Dao's dependency injection

When writing a program, through inversion of control, the creation of objects is handed over to Spring, but it is impossible to have no dependencies in the code. IOC decoupling just reduces their dependencies, but does not eliminate them. For example: the business layer will still call the method of the persistence layer.

Then this kind of dependency between the business layer and the persistence layer, after using Spring, let Spring maintain it.
To put it simply, it is to wait for the framework to pass the persistence layer object to the business layer instead of obtaining it ourselves.

How to inject UserDao into UserService?

  • Construction method
  • set method

Construction method:

Add a constructor to UserServiceImpl:

    private UserDao userDao;
//    有参构造
    public UserServiceImpl(UserDao userDao) {
    
    
        this.userDao = userDao;
    }
//    无参构造
    public UserServiceImpl() {
    
    
    }

Configure in the configuration file:

    <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl"  ></bean>
       <bean id="userService" class="com.xy.service.impl.UserServiceImpl">
            <constructor-arg name="userDao" ref="userDao"></constructor-arg>
       </bean>
<!--    name中的userDao是构造内部的参数名-->

operation result:

insert image description here

set method:

Add the set method in UserServiceImpl:

    private UserDao userDao;
//    快捷键Ctrl+Insert+fn-->setter
    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }

    public void save() {
    
    
        userDao.save();
    }

Configure in the configuration file to tell the Spring container to inject Dao in the container (injected through the set method) to the Service:

    <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl"  ></bean>
    <bean id="userService" class="com.xy.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
<!--name指UserServiceImpl中的setUserDao方法set后面的UserDao,并把开头字母小写-->
<!--ref中的userDao 是指id的UserDao-->

operation result:

insert image description here

P namespace injection:
the essence is set method injection, but it is more convenient than the above set method injection, mainly reflected in the configuration file:

First, the P namespace needs to be introduced:

xmlns:p="http://www.springframework.org/schema/p"

insert image description here

Second, modify the injection method:

    <bean id="userService" class="com.xy.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>

operation result:

insert image description here

7. Bean dependency injection data type

The above operations are all injected reference beans, except that object references can be injected, common data types, collections, etc. can be injected in the container.

Three data types of injected data:

  • common data type
  • reference data type
  • collection data type

Common data types:

Modify the code in userDaoImpl to:

public class UserDaoImpl implements UserDao {
    
    
    private String username;
    private int age;
//生成setter方法
    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public void save() {
    
    
        System.out.println(username+"===="+age);
        System.out.println("save running...");
    }
}

In the configuration file:

    <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl"  >
        <property name="username" value="zhangsan"/>
        <property name="age" value="18"/>
    </bean>
<!--    ref是指引用类型的注入,value是普通类型的注入,这里用value-->

Execute the code in the UserController test class, and the running results are as follows:
insert image description here

Collection data type:

Create a User class:

insert image description here
Write several attributes and get, set, tostring methods in the User class:

public class User {
    
    
    
    private String name;
    private String addr;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getAddr() {
    
    
        return addr;
    }

    public void setAddr(String addr) {
    
    
        this.addr = addr;
    }
    
    @Override
    public String toString() {
    
    
        return "User{" +
                "name='" + name + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }

}

Create several collections and set methods in UserDaoImpl, as well as output, the code is as follows:

//    集合类型
    private List<String> strList;
    private Map<String, User> userMap;
    private Properties properties;
//三个set方法
    public void setStrList(List<String> strList) {
    
    
        this.strList = strList;
    }

    public void setUserMap(Map<String, User> userMap) {
    
    
        this.userMap = userMap;
    }

    public void setProperties(Properties properties) {
    
    
        this.properties = properties;
    }
    public void save() {
    
    
//        System.out.println(username+"===="+age);
        System.out.println(strList);
        System.out.println(userMap);
        System.out.println(properties);
        System.out.println("save running...");
    }

Profile configuration:

        <bean id="userDao" class="com.xy.dao.impl.UserDaoImpl"  >
        <property name="strList" >
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
        <property name="userMap">
            <map>
                <entry key="u1" value-ref="user1"></entry>
                <entry key="u2" value-ref="user2"></entry>
            </map>
        </property>
        <property name="properties">
            <props>
                <prop key="p1">ppp1</prop>
                <prop key="p2">ppp2</prop>
                <prop key="p3">ppp3</prop>
            </props>
        </property>
    </bean>


    <bean id="user1" class="com.xy.domain.User">
        <property name="name" value="tom"></property>
        <property name="addr" value="beijing"></property>
    </bean>
    <bean id="user2" class="com.xy.domain.User">
        <property name="name" value="lucy"></property>
        <property name="addr" value="tianjing"></property>
    </bean>

operation result:

insert image description here

8. Introduce other configuration files (sub-module development)

In actual development, Spring has a lot of configuration content, which makes Spring configuration very complicated and large in size. Therefore, part of the configuration can be disassembled into other configuration files, and in the Spring main configuration file, and in the Spring main configuration Files are loaded via the import tag

Create two configuration files:
insert image description here
other configuration files can be loaded through import in the main configuration file:

    <import resource="applicationContext-user.xml"/>
    <import resource="applicationContext-product.xml"/>

Key configuration of Spring

insert image description here

Guess you like

Origin blog.csdn.net/weixin_47678894/article/details/126077240
Recommended