Spring learning -- Spring Bean management

Posted by tsabar on Mon, 31 Jan 2022 16:59:36 +0100

Spring Bean management

xml based configuration mode

bean configuration requires spring managed classes
id generated object name
Class full class name
name object alias, which can be multiple
scope:
Singleton (default): there is only one bean instance in Spring, singleton mode Prototype: when the prototype getBean(), new Bean()
Request: each http request will create a bean, which is only used for WebApplicationContext
environment
Session: the same http session shares a Bean. Different sessions use different beans. The use environment is the same as above

Xml configuration mode Dependency Injection [DI: Dependency Injection]

Setting the object dependency attribute to the object through configuration requires DI support to implement IOC

Injection method:

1.set injection

We create a user class and write properties (generate get set methods)

package com.spring0.bean;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class User {

    private int id;
    private String name;
    private Phone phone;//Custom class properties

    private List list;
    private Map map;
    private Set set;
    private Properties properties;//This class is the tag used to encapsulate properties

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public Set getSet() {
        return set;
    }

    public void setSet(Set set) {
        this.set = set;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Phone getPhone() {
        return phone;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }

    public User() {
        System.out.println("User Construction method");
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone=" + phone +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                ", properties=" + properties +
                '}';
    }
}

Create an xml file to inject values into the user object using the set method

<?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">
    <!-- Dependency injection  DI
        stay spring When the frame creates an object,You can assign values to attributes in an object(Injection value)
        Mode 1:By attribute set Method injection
       -->
    <bean id="phone" class="com.spring0.bean.Phone" ></bean>
    <bean id="user" name="user1,user2"  class="com.spring0.bean.User" scope="prototype">
        <property name="id" value="1" ></property>
        <property name="name" value="admin"></property>
        <property name="phone" ref="phone"></property>
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="key1" value="val1"></entry>
                <entry key="key2" value="val2"></entry>
                <entry key="key3" value="val3"></entry>
            </map>
        </property>

        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
            </set>
        </property>

        <property name="properties">
            <props>
                <prop key="key1">key1</prop>
                <prop key="key2">key2</prop>
                <prop key="key3">key3</prop>
            </props>
        </property>
      </bean>
</beans>

test

package com.spring0.test;

import com.spring0.bean.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    /*
            IOC  Control reversal
            Take control of (create an object)
            Flip to (spring framework, spring container)
         */
    public static void main(String[] args) {
        //Creating spring container ClassPathXmlApplicationContext is one of the upper interfaces of the implementation class ApplicationContext
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = (User) applicationContext.getBean("user");
        System.out.println(user);
    }
}

Operation results

User Construction method
User{id=1, name='admin', phone=com.spring0.bean.Phone@4f970963, list=[list1, list2, list3], map={key1=val1, key2=val2, key3=val3}, set=[set1, set2], properties={key3=key3, key2=key2, key1=key1}}

2. Construction method

//Create a constructor with parameters in the user class
package com.spring0.bean;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class User {

    private int id;
    private String name;
    private Phone phone;

    public User(int id, String name, Phone phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public User() {
        System.out.println("User Construction method");
    }
}
<?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">

    <!--
        Injection of construction method
    -->
    <bean id="phone" class="com.spring0.bean.Phone"></bean>
    <bean id="user" name="user1,user2" class="com.spring0.bean.User" scope="prototype">
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="name" value="admin"></constructor-arg>
        <constructor-arg name="phone" ref="phone"></constructor-arg>
    </bean>
</beans>

test result

User{id=1, name='admin', phone=com.spring0.bean.Phone@67b92f0a}

Annotation implementation

The annotation function is encapsulated in the AOP package and can be imported into the Spring aop jar package

Enable annotation scanning

1. In spring Add constraint address to XML

Each time you create an xml file, you can import all the contents

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
</beans>

2. Enable annotation scanning

<context:component-scan base-package="Package name"> < /context:component-scan>

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qa2z2c6y-1623561101045) (C: \ users \ 17509 \ appdata \ roaming \ typora \ typora user images \ 1622533301757. PNG)]

Annotation creation object
@Component(value = "user") equals < bean id = "user" class = "" > < / bean >

package com.spring0.bean;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

@Component(value = "user ")
public class User {

    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

@Service

package com.spring0.service;

import org.springframework.stereotype.Service;

@Service(value = "userSerivice")
public class Usersrvice {

}

@Repository

package com.spring0.dao;

import org.springframework.stereotype.Repository;

@Repository(value = "userDao")
public class UserDao {
    public void save(){
        System.out.println("Save user");
    }
}

Annotation method injection attribute [DI: Dependency Injection]

@Autowired

package com.spring0.service;

import com.spring0.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service(value = "userSerivice")
public class Usersrvice {

    //Annotation label of spring framework
   
    /*
    There are two ways to find the value to be injected
    1.byType  According to the attribute type, find in the spring container
    @Autowired(required = true)  The attribute value of default injection cannot be empty
	
    2.byName   @Qualifier(value = "userDao")Search by @ Repository(value = "userDao") name*/
    @Autowired
    @Qualifier(value = "userDao")
    UserDao userDao;
     
    public void save() {
        userDao.save();
    }
}

JDK annotation @ Resource auto injection

Spring provides support for @ Resource annotation in jdk.

@Resource annotations can match beans by name or type. By default, reference type properties are automatically injected by byName

@If the Resource annotation specifies its name attribute, the value of name is the id of the Bean matched by name.

package com.spring0.service;

import com.spring0.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service(value = "userSerivice")
public class Usersrvice {
    /*
    @Resource  JDK The self-contained annotation label is injected with byName
     */
    @Resource(name = "userDao")
    UserDao userDao;

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

Comparison between annotation and XML

  1. Annotation advantages: convenient, intuitive and efficient
  2. Disadvantages of annotation: it is written into Java code by hard coding, and the modification needs to recompile the code
  3. The advantage of xml is that the configuration and code are separated. If you modify them in xml, you don't need to compile the code. You just need to restart the server to load the new configuration.
  4. The disadvantages of xml are: writing is cumbersome, inefficient, and large-scale projects are too complex

Topics: Java Mybatis Spring ioc