Location>code7788 >text

spring - Xml-based configuration bean notes

Popularity:940 ℃/2024-10-09 17:09:00

4, Spring Content

 

 

 

7, Quick Start

Demand:pass (a bill or inspection etc)Spring modalities[configuration file]GetJavaBean: Monster object, and assigns the object attributes to thevalue, output information about the object.

Code Structure:

The lib directory is self-created, and then 5 more jar packages are brought in

 

Source Code:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--
            The old Han interpretation
            1. configure monster object/javabean
            2. in beans can be configured multiple beans
            3. bean means a java object
            4. class attribute is used to specify the full path of the class -> spring underlying the use of reflection to create
            5. id property indicates the id of the java object in the spring container, through the id you can get the object
            6. <property name="monsterId" value="100"> used to assign a value to the object's properties, not given is the default value
-->
    <bean class="" id="monster01">
        <property name="monsterID" value="100"/>
        <property name="name" value= "King Bull"/>
        <property name="skill" value= "Banana Fan"/>
    </bean>
</beans>

 

package ;

public class Monster {
    private Integer monsterID;
    private String name;
    private String skill;

    //full-parameter constructor (math.)
    public Monster(Integer monsterID, String name, String skill) {
        this.monsterID = monsterID;
        this.name = name;
        this.skill = skill;
    }

    //A parameterless constructor must be written, and Spring reflection is required to create an object using the
    public Monster() {

    }

    public Integer getMonsterID() {
        return monsterID;
    }

    public void setMonsterID(Integer monsterID) {
        this.monsterID = monsterID;
    }

    public String getName() {
        return name;
    }

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

    public String getSkill() {
        return skill;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "monsterID=" + monsterID +
                ", name='" + name + '\'' +
                ", skill='" + skill + '\'' +
                '}';
    }
}

 

package ;

import ;
import ;
import ;
import ;

public class SpringBeanTest {

    @Test
    public void getMonster() {
        //1. Create the container ApplicationContext
//2. The container is associated with a container profile
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");

        //3. Get the corresponding object through getBean
//   The default return is Object , but the runtime type Monster
        Object monster01 = ("monster01");

        //4. Outputs
        ("monster01=" + monster01);
        ("Run Type = " + ());

        //5. You can also specify the Class type directly when you get it again, so you can get it again.
        Monster monster02 = ("monster01", Monster.class);
        ("monster01=" + monster01);
        ("Run Type = " + ());
    }
}

 

Run results:

 

11, Spring container structure analysis

 

 

 

25, Spring configuration of the basic introduction to the bean

 

26, Getting Beans by Type

The previous quickstart was to get the bean by id

The code structure, it's all the same.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configure Monster, get it by type, require only one bean of the same class in the ioc container, otherwise an exception will be thrown.-->
    <bean class="">
        <!--Lao Han interpretation
        1. When we set a property on a bean object, we use the corresponding setter method.
        2. the bottom is to use the corresponding setter method to complete, such as setName ()
        3. If there is no such method, an error will be reported.
-->
        <property name="monsterID" value="100"/>
        <property name="name" value= "King Bull"/>
        <property name="skill" value= "Banana Fan"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;

public class SpringBeanTest {

    //Getting objects by bean type
    @Test
    public void getBeanByType() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        //Teacher paraphrase, pass in class object/type directly
        Monster bean = (Monster.class);
        ("bean=" + bean);
    }
}

 

Running results:

 

28, Configuring Beans by Specifying Constructors

No change in code structure

package ;

public class Monster {
    private Integer monsterID;
    private String name;
    private String skill;

    //full-parameter constructor (math.)
    public Monster(Integer monsterID, String name, String skill) {
        ("Monster full-parameter constructor called...");
        this.monsterID = monsterID;
        this.name = name;
        this.skill = skill;
    }

    //A parameterless constructor must be written, and Spring reflection is required to create an object using the
    public Monster() {

    }

    public Integer getMonsterID() {
        return monsterID;
    }

    public void setMonsterID(Integer monsterID) {
        this.monsterID = monsterID;
    }

    public String getName() {
        return name;
    }

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

    public String getSkill() {
        return skill;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "monsterID=" + monsterID +
                ", name='" + name + '\'' +
                ", skill='" + skill + '\'' +
                '}';
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configure the Monster object and specify the constructor
    Teacher Interpretation
    1. the constructor-arg tag specifies the parameters of the constructor to be used.
    2. index indicates the first argument of the constructor, counting from 0.
    3. In addition to index, you can also specify the type of arguments by name / type.
    4. To clear up the confusion, class constructors cannot have constructors of exactly the same type and order, so they can be specified by type.
-->
    <bean class="" id = "monster01">
        <constructor-arg value="200" index="0"/>
        <constructor-arg value= "White Bones" index="1"/>
        <constructor-arg value= "Sucking human blood" index="2"/>
    </bean>
    <bean class="" id="monster02">
        <constructor-arg value="200" name="monsterID"/>
        <constructor-arg value= "White Bones" name="name"/>
        <constructor-arg value= "Sucking human blood" name="skill"/>
    </bean>
    <!--
    The datatype is the corresponding Java datatype, in the order of constructor parameters.
-->
    <bean class="" id="monster03">
        <constructor-arg value="200" type=""/>
        <constructor-arg value= "White Bones" type=""/>
        <constructor-arg value= "Sucking human blood" type=""/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;

public class SpringBeanTest {

    //Setting properties via constructors
    @Test
    public void setBeanByConstructor() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Monster bean = ("monster01", Monster.class);
        ("bean=" + bean);
    }
}

 

Run results:

 

30, Configuring Beans via refs

 The dao attribute of the Service object wants to refer to the dao in the right container, which is a cross-reference to the bean object via ref.

 

 

Code Structure:

 

package ;

//dao object
public class MemberDAOImpl {
    //constructor
    public MemberDAOImpl() {
        ("The MemberDAOImpl constructor was executed...");
    }

    public void add() {
        ("The MemberDAOImpl add() method was executed...");
    }
}

 

package ;

import ;

public class MemberServiceImpl {
    private MemberDAOImpl memberDAO;

    public MemberDAOImpl getMemberDAO() {
        return memberDAO;
    }

    public void setMemberDAO(MemberDAOImpl memberDAO) {
        this.memberDAO = memberDAO;
    }

    public void add() {
        ("MemberServiceImpl add() was called...");
        ();
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configure the MemberDAOImpl object-->
    <bean class="" id="memberDAO"/>
    <!--Configuring MemberServiceImpl Objects
            Lao Han interpretation
            1. ref="memberDAO" indicates that the object referenced by the MemberServiceImpl object attribute memberDAO is the object with id=memberDAO
            The object with id=memberDAO
            2. This reflects the dependency injection of the spring container.
            3. Note that the spring container, he is as a whole to the implementation, that is, if you refer to a bean object, you configure the order of no requirements
            4. It is recommended that the order, the advantage is to read the time, more convenient
-->
    <bean class="" id="memberService">
        <property name="memberDAO" ref="memberDAO"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;

public class SpringBeanTest {

    //Setting bean attributes via ref
    @Test
    public void setBeanByRef() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        MemberServiceImpl memberService = ("memberService", MemberServiceImpl.class);
        ();
    }
}

 

Run results:

 

32, Configuring properties through internal beans

The structure of the code in the previous section remains unchanged, with only changes to the and

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring MemberServiceImpl Objects - Using Internal Beans-->
    <bean class="" id="memberService">
        <!--Configure an internal bean yourself-->
        <property name="memberDAO">
            <bean class=""/>
        </property>
    </bean>

</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;

public class SpringBeanTest {

    //Setting properties via internal beans
    @Test
    public void setBeanByPro() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        MemberServiceImpl memberService = ("memberService", MemberServiceImpl.class);
        ();
    }
}

 

Run results:

 

33, configure the List property

 

Code Structure:

 

package ;

import .*;

public class Master {
    private String name;

    private List<Monster> monsterList;
    private Map<String, Monster> monsterMap;
    private Set<Monster> monsterSet;

    //arrays
    private String[] monsterName;

    //Java Basics
//This Properties is a subclass of Hashtable and is of the form key-value.
//Here, the Properties key and value are both String.
    private Properties pros;

    public String getName() {
        return name;
    }

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

    public List<Monster> getMonsterList() {
        return monsterList;
    }

    public void setMonsterList(List<Monster> monsterList) {
        this.monsterList = monsterList;
    }

    public Map<String, Monster> getMonsterMap() {
        return monsterMap;
    }

    public void setMonsterMap(Map<String, Monster> monsterMap) {
        this.monsterMap = monsterMap;
    }

    public Set<Monster> getMonsterSet() {
        return monsterSet;
    }

    public void setMonsterSet(Set<Monster> monsterSet) {
        this.monsterSet = monsterSet;
    }

    public String[] getMonsterName() {
        return monsterName;
    }

    public void setMonsterName(String[] monsterName) {
        this.monsterName = monsterName;
    }

    public Properties getPros() {
        return pros;
    }

    public void setPros(Properties pros) {
        this.pros = pros;
    }

    @Override
    public String toString() {
        return "Master{" +
                "name='" + name + '\'' +
                ", \nmonsterList=" + monsterList +
                ", \nmonsterMap=" + monsterMap +
                ", \nmonsterSet=" + monsterSet +
                ", \nmonsterName=" + (monsterName) +
                ", \npros=" + pros +
                '}';
    }
}

 

package ;

public class Monster {
    private Integer monsterID;
    private String name;
    private String skill;

    //full-parameter constructor (math.)
    public Monster(Integer monsterID, String name, String skill) {
        this.monsterID = monsterID;
        this.name = name;
        this.skill = skill;
    }

    //A parameterless constructor must be written, and Spring reflection is required to create an object using the
    public Monster() {

    }

    public Integer getMonsterID() {
        return monsterID;
    }

    public void setMonsterID(Integer monsterID) {
        this.monsterID = monsterID;
    }

    public String getName() {
        return name;
    }

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

    public String getSkill() {
        return skill;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "monsterID=" + monsterID +
                ", name='" + name + '\'' +
                ", skill='" + skill + '\'' +
                '}';
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring Master Objects
    Experience spring container configuration features Dependency Injection - very flexible
-->
    <bean class="" id="master">
        <property name="name" value= "Supreme Lord."/>
        <!--Assigning a value to the list attribute-->
        <property name="monsterList">
            <list>
                <ref bean="monster01"/>
                <bean class="">
                    <property name="monsterID" value="100"/>
                    <property name="name" value= "Mouseketeer"/>
                    <property name="skill" value= "Eat food"/>
                </bean>
            </list>
        </property>
    </bean>

    <bean class="" id="monster01">
        <property name="monsterID" value="1001"/>
        <property name="name" value= "King Bull"/>
        <property name="skill" value= "Banana Fan"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;

public class SpringBeanTest {

    //Assigning Values to Collection Array Properties
    @Test
    public void setBeanByCollection() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Master master = ("master", Master.class);
        ("master=" + master);
    }
}

 

Running results:

 

35, configure the Map property

The structure of the code is the same as in the previous section, except for the change of the

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring Master Objects
    Experience spring container configuration features Dependency Injection - very flexible
-->
    <bean class="" id="master">
        <property name="name" value= "Supreme Lord."/>
        <!--Assigning a value to the map attribute-->
        <property name="monsterMap">
            <map>
                <entry>
                    <key>
                        <value>monster01</value>
                    </key>
                    <!--Here the teacher uses an external bean, introducing the-->
                    <ref bean="monster01"/>
                </entry>

                <entry>
                    <key>
                        <value>monster02</value>
                    </key>
                    <!--Here the teacher uses an external bean, introducing the-->
                    <ref bean="monster02"/>
                </entry>
            </map>
        </property>
    </bean>

    <bean class="" id="monster01">
        <property name="monsterID" value="1001"/>
        <property name="name" value= "King Bull"/>
        <property name="skill" value= "Banana Fan"/>
    </bean>

    <bean class="" id="monster02">
        <property name="monsterID" value="1002"/>
        <property name="name" value= "Red Child"/>
        <property name="skill" value= "Play"/>
    </bean>
</beans>

 

Run results:

 

36, configuring the Set property

The code structure remains the same, only the

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring Master Objects
    Experience spring container configuration features Dependency Injection - very flexible
-->
    <bean class="" id="master">
        <property name="name" value= "Supreme Lord."/>
        <!--Assigning a value to the set property-->
        <property name="monsterSet">
            <set>
                <ref bean="monster01"/>
                <bean class="">
                    <property name="monsterID" value="666"/>
                    <property name="name" value= "The Golden Horn."/>
                    <property name="skill" value= "Spit."/>
                </bean>
            </set>
        </property>
    </bean>

    <bean class="" id="monster01">
        <property name="monsterID" value="1001"/>
        <property name="name" value= "King Bull"/>
        <property name="skill" value= "Banana Fan"/>
    </bean>
</beans>

 

Run results:

 

37, configure the Array property

The code structure remains the same, only the

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring Master Objects
    Experience spring container configuration features Dependency Injection - very flexible
-->
    <bean class="" id="master">
        <property name="name" value= "Supreme Lord."/>
        <!--Assigning values to array attributes
        One more thing: whether to use value or bean in array tags, ref . Depending on your business, an array can be a string array or a Map array.
-->
        <property name="monsterName">
            <array>
                <value>hobgoblin</value>
                <value>monster</value>
                <value>old devil</value>
            </array>
        </property>
    </bean>
</beans>

 

Run results:

 

38, Configuring Properties Properties

The code structure remains the same, only the

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">
    <!--Configuring Master Objects
    Experience spring container configuration features Dependency Injection - very flexible
-->
    <bean class="" id="master">
        <property name="name" value= "Supreme Lord."/>
        <!--Assigning values to Properties properties Structure k(String)-v(String)-->
        <property name="pros">
            <props>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
                <prop key="ip">127.0.0.1</prop>
            </props>
        </property>
    </bean>
</beans>

 

Run results:

 

39, configured using util:list

Code Structure:

 

package ;

import ;

public class BookStore {
    private List<String> bookList;

    //A parameterless constructor, which can be left out if you don't have any other constructors.
//But if you have other constructors, you have to explicitly define a referenceless constructor.
    public BookStore() {
    }

    public BookStore(List<String> bookList) {
        this.bookList = bookList;
    }

    public List<String> getBookList() {
        return bookList;
    }

    public void setBookList(List<String> bookList) {
        this.bookList = bookList;
    }

    @Override
    public String toString() {
        return "BookStore{" +
                "bookList=" + bookList +
                '}';
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Define a util:list and specify ids to reuse data.
    Teacher's note: When using the util:list namespace, you need to introduce the appropriate tags, usually by alt + enter will automatically add the
    , if not, just add it manually.
-->
    <util:list id="myBookList">
        <value>Three Kingdoms period (220-280) in Chinese history</value>
        <value>The Dream of the Red Chamber (Suzhou, Jiangsu province)</value>
        <value>also called Pilgrimage the West or Monkey</value>
        <value>seashore</value>
    </util:list>

    <!--Configuring BookStore Objects-->
    <bean class="" id="bookStore">
        <property name="bookList" ref="myBookList"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Assigning values to properties using the util:list namespace
    @Test
    public void setBeanByUtilList() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        BookStore bookStore = ("bookStore", BookStore.class);
        ("bookStore=" + bookStore);
    }
}

 

Results.

 

40, Attribute Cascade Assignment Configuration

That is, when configuring an object of class A, class A has a class B attribute, and at the same time assigns a value to the name of the class B attribute.

Example: The Employee class has a department attribute, and when configuring an employee, specify by the way what the department name of this employee is

Code Structure:

 

package ;

//sectoral category
public class Dept {
    private String name;

    public Dept() {
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Dept{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

package ;

//employee category
public class Emp {
    private String name;
    private Dept dept;

    public Emp() {
    }

    public String getName() {
        return name;
    }

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

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", dept=" + dept +
                '}';
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Configuring the Dept Object-->
    <bean class="" id="dept"/>
    <!--Configuring Emp Objects-->
    <bean class="" id="emp">
        <property name="name" value="jack"/>
        <property name="dept" ref="dept"/>
        <!--Here I want to assign a value to the name attribute of dept [cascading attribute assignment]-->
        <property name="" value= "Java Development Department"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Cascading Assignments to Properties
    @Test
    public void setBeanByRelation() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Emp emp = ("emp", Emp.class);
        ("emp=" + emp);
    }
}

 

Run results:

 

41, Getting Beans through Static Factories

 

Code Structure:

 

package ;

import ;

import ;
import ;

//Static factory class - can return Monster objects
public class MyStaticFactory {
    private static Map<String, Monster> monsterMap;

    //Use static blocks for initialization
//In java fundamentals, the lecture on the
    static {
        monsterMap = new HashMap<>();
        ("monster01", new Monster(100, "King Bull", "Banana Fan")));
        ("monster02", new Monster(200, "vixen", "beauty queen")));
    }

    //Provide a method that returns the Monster object
    public static Monster getMonster(String key) {
        return (key);
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Configure monster object, get it from static factory
    Teacher's explanation
    1. get/configure bean through static factory
    2. class is the full path to the static factory class.
    3. factory-method means to specify which method of the static factory class returns the object.
    4. constructor-arg value="monster02" value specifies which object of the static factory is to be returned.
-->
    <bean id="my_monster01" class=""
          factory-method="getMonster">
        <constructor-arg value="monster01"/>
    </bean>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Cascading Assignments to Properties
    @Test
    public void setBeanByRelation() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Monster monster = ("my_monster01", Monster.class);
        ("monster=" + monster);
    }
}

 

Run results:

 

42, Getting Beans through Instance Factories

 

Code Structure:

(math.) invariant

 

package ;

import ;

import ;
import ;

public class MyInstanceFactory {
    private Map<String, Monster> monster_Map;

    //Initialization via common code blocks
    {
        monster_Map = new HashMap<>();
        monster_Map.put("monster03", new Monster(100, "Bull Demon King~", "Banana Fan~"));
        monster_Map.put("monster04", new Monster(200, "Vixen~", "Beautycatcher~"));
    }

    //Provide a method that returns the Monster object
    public Monster getMonster(String key) {
        return monster_Map.get(key);
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Configuring monster objects, via instance factories
    Lao Han interpretation
    1. factory-bean Specifies which instance factory object is used to return the bean.
    2. factory-method Specifies which method of the instance factory object is used to return the bean.
    3. constructor-arg value="monster03" specifies which monster in the instance factory to get.
-->
    <bean class="" id="myInstanceFactory"/>
    <bean id="my_monster01" factory-bean="myInstanceFactory" factory-method="getMonster">
        <constructor-arg value="monster03"/>
    </bean>
</beans>

 

Run results:

 

44, Getting Beans via FactoryBean

Code Structure:

(math.) invariant

 

package ;

import ;
import ;

import ;
import ;

public class MyFactoryBean implements FactoryBean<Monster> {
    //This key is the key of the object you specify to fetch when configuring the
    private String key;
    private Map<String, Monster> monster_map;

    //Code block to complete the initialization
    {
        monster_map = new HashMap<>();
        monster_map.put("monster03", new Monster(100, "Bull Demon King~", "Banana Fan~"));
        monster_map.put("monster04", new Monster(200, "Vixen~", "Beautycatcher~"));
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public Monster getObject() throws Exception {
        return monster_map.get(key);
    }

    @Override
    public Class<?> getObjectType() {
        return Monster.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Configure monster object, get it via FactoryBean
    Teacher's explanation
    1. class specifies the FactoryBean to be used.
    2. key is the key of the MyFactoryBean attribute.
    3. value is the key of the object you want to get.
-->
    <bean id="my_monster01" class="">
        <property name="key" value="monster04"/>
    </bean>
</beans>

 

Run results:

 

45, Bean Configuration Information Reuse

 

The code structure remains the same.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Configuring Monster Objects
    1. If a bean is specified with abstract="true", it means that the bean object, which is specifically designed to be inherited, cannot be acquired/instantiated.
    2. The bean itself cannot be fetched/instantiated.
-->
    <bean id="monster12" class="" abstract="true">
        <property name="monsterID" value="100"/>
        <property name="name" value= "Centipede Spirit~"/>
        <property name="skill" value= "Sting." = "Sting."/>
    </bean>

    <!--Configuring Monster Objects-->
    <bean id="monster10" class="">
        <property name="monsterID" value="10"/>
        <property name="name" value= "Centipede Spirit"/>
        <property name="skill" value= "Sting"/>
    </bean>
    <!--
        Lao Han explains
        1. Configure the Monster object
        2. But the property value of this object is the same as the object property.
        = "monster10" Specifies that the current configured object's attribute values come from the object with id=monster10.
-->
    <bean id="monster11" class=""
          parent="monster10"/>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Get bean via FactoryBean
    @Test
    public void getBeanByExtends() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Monster monster11 = ("monster11", Monster.class);
        ("monster11=" + monster11);
    }
}

 

Run results:

 

46, Bean creation order 1

 

Code Structure:

 

package ;

public class Student {
    public Student() {
        ("The Student() constructor is executed...");
    }
}

package ;

public class Department {
    public Department() {
        ("The Department() constructor is executed...");
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">
    <!--Test the order in which bean objects are created
    Teacher interpretation
    1. By default, beans are created in the order they are configured.
    2. but if we add depends-on="department01", then the id= department01 object will be created first.
-->
    <bean id="student01" class="" depends-on="department01"/>
    <bean id="department01" class=""/>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Test Bean Creation Order
    @Test
    public void testBeanByCreate() {

        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        ("ok");
    }
}

 

Running results:

 

47, Bean creation order 2

The code structure is the same as in section 30, , , , changed

package ;

import ;

public class MemberServiceImpl {
    private MemberDAOImpl memberDAO;

    public MemberServiceImpl() {
        ("The MemberServiceImpl() constructor is executed...");
    }

    public MemberDAOImpl getMemberDAO() {
        return memberDAO;
    }

    public void setMemberDAO(MemberDAOImpl memberDAO) {
        ("setMemberDAO()...");
        this.memberDAO = memberDAO;
    }

    public void add() {
        ("MemberServiceImpl add() was called...");
        ();
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">

    <bean class="" id="memberService">
        <property name="memberDAO" ref="memberDAO"/>
    </bean>
    <bean class="" id="memberDAO"/>
</beans>

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Test Bean Creation Order
    @Test
    public void testBeanByCreate() {

        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        ("ok");
    }
}

 

Running results:

 

48, Single and Multiple Instances of Beans

 

The usage details need to be debugged.

 

 

Code Structure:

 

package ;

public class Cat {
    private Integer id;
    private String name;

    public Cat() {
        ("Cat() was executed...");
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">

    <!--Configuring Cat Objects
        Teacher's explanation
        1. By default, the scope attribute is singleton.
        2. in the ioc container, as long as there is a bean object
        3. when the programmer executes the getBean, the return is the same object
        4. if we want a new bean object to be returned each time we get a bean, we can use scope="prototype".
        5. if the bean is configured with scope="singleton" lazy-init="true" then the ioc container will not create the object in advance, but will create it when the getBe is executed.
           , the object is created when the getBean method is executed.
-->
    <bean id="cat" class="" scope="prototype">
        <property name="id" value="100"/>
        <property name="name" value= "Kitten"/>
    </bean>
</beans>

 

package ;

import .*;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Test Scope
    @Test
    public void testBeanScope() {

        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");

        Cat cat = ("cat", Cat.class);
        Cat cat2 = ("cat", Cat.class);
        Cat cat3= ("cat", Cat.class);

        ("cat=" + cat);
        ("cat=" + cat2);
        ("cat=" + cat3);
    }
}

 

Run results:

 

50, Bean life cycle

 

Code Structure:

 

package ;

public class House {
    private String name;

    public House() {
        ("House() constructor");
    }

    public String getName() {
        return name;
    }

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

    //The following two methods are written by programmers, according to their own business logic, and the names are not fixed
    public void init() {
        ("House init()...");
    }

    public void destroy() {
        ("House destory()...");
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/">

    <!--Configure House objects to demonstrate the entire bean lifecycle
    Teacher's explanation
    1. init-method="init" specifies the initialization method of the bean, which is executed after the setter method.
    2. init-method execution timing, spring container control
    3. destroy-method="destroy" specifies the bean's destruction method, which is executed when the container is closed.
    4. The timing of the destroy method is controlled by the spring container.
-->
    <bean class="" id="house" init-method="init" destroy-method="destroy">
        <property name="name" value= "Beijing Mansions"/>
    </bean>
</beans>

 

package ;

import .*;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Testing the Life Cycle of a Bean
    @Test
    public void  testBeanLife() {

        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        House house = ("house", House.class);
        ("Use house=" + house);

        //Close the container
//1. Here again, we need to examine the java foundation, with the form of interface
//2. ioc compile type ApplicationContext , run type ClassPathXmlApplicationContext
//3. Because ClassPathXmlApplicationContext implements ConfigurableApplicationContext.
//4. ClassPathXmlApplicationContext has close
//5. ioc into ClassPathXmlApplicationContext, then call close
//();
        //Close the ioc container.
        ((ConfigurableApplicationContext)ioc).close();

    }
}

 

Run results:

 

51, Configuring Bean Postprocessors

 

 

Code Structure:

 

package ;

public class House {
    private String name;

    public House() {
        ("House() constructor");
    }

    public String getName() {
        return name;
    }

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

    //The following two methods are written by programmers, according to their own business logic, and the names are not fixed
    public void init() {
        ("House init()...");
    }

    public void destroy() {
        ("House destory()...");
    }

    @Override
    public String toString() {
        return "House{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

package ;

import ;
import ;

//This is a post processor, you need to implement the BeanPostProcessor interface
public class MyBeanPostProcessor implements BeanPostProcessor {
    /**
     * When is it called: before the bean's init method, to accomplish certain tasks before initialization
     *@param bean : the incoming bean created/configured in the IOC container.
     * is the bean object returned by the ioc container, if it is modified by the replacement here, then the returned bean object will be modified as well.
     *bean : the bean object returned by the ioc container.@param beanName: The id passed in to create/configure the bean in the IOC container.
     * is the name of the bean configured by the ioc container
     *@return Object: the programmer modifies/processes the incoming bean [if necessary], returning
     * is the returned bean object
*/
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ("postProcessBeforeInitialization()... bean="
                + bean + " beanName=" + beanName);

        //Initial experience case: if the type is House uniformly changed to Shanghai mansion
//Handling/programming of multiple objects --> faceted programming
        if (bean instanceof House) {
            ((House)bean).setName("Shanghai Mansion.");
        }
        return bean;
    }

    /**
    * When is it called: after the bean is initialized to complete certain tasks.
    *@param bean : is the bean object returned by the ioc container, if it is modified by the replacement here, the bean object returned will also be modified.
    bean: is the bean object returned by the ioc container, if it is modified by replacing it here, then the bean object returned will also be modified
    *The@param beanName: is the name of the bean configured by the ioc container
    *@return Object: is the bean object returned
*/
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        ("postProcessAfterInitialization()... bean="
                + bean + " beanName=" + beanName);
        return bean;
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans /schema/beans/">

    <!--Configuring House Objects-->
    <bean class="" id="house"
          init-method="init"
          destroy-method="destroy">
        <property name="name" value= "Grand Mansion"/>
    </bean>

    <bean class="" id="house02"
          init-method="init"
          destroy-method="destroy">
        <property name="name" value= "* Mansions"/>
    </bean>

    <!--Configuring Post Processor Objects
    Teacher's explanation
    1. When we configure MyBeanPostProcessor in the container configuration file, the post processor object will act on the bean object created by the container.
    2. The post processor object will then act on the bean object created by the container
    3. has been programmed for all objects -> cutter programming AOP
-->
    <bean class="" id="myBeanPostProcessor"/>
</beans>

 

package ;

import .*;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    @Test
    public void beanPostProcessor() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");

        House house = ("house", House.class);
        ("Use house=" + house);

        House house02 = ("house", House.class);
        ("Use house02=" + house02);
        ((ConfigurableApplicationContext)ioc).close();
    }
}

 

Run results:

 

54, Configuring Beans via Properties Files

Code Structure:

 

monsterID=1000
name=jack
skill=hello

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xmlns:context="/schema/context"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/ /schema/context /schema/context/">

    <!--Specifying the properties file
    "location="classpath:" means specify the location of the properties file
    Need to bring classpath
    Properties file has Chinese characters, need to convert it to unicode --> use online tools to convert
-->
    <context:property-placeholder location="classpath:"/>
    <!--Configuring Monster Objects
    1. Assign values to the properties of the monster object via the properties file.
    2. This time, our attribute values are passed through ${attribute name}.
    3. The property name we're talking about here is the k in k=v in the file.
-->
    <bean class="" id="monster1000">
        <property name="monsterID" value="${monsterID}"/>
        <property name="skill" value="${skill}"/>
        <property name="name" value="${name}"/>
    </bean>
</beans>

 

 

package ;

import .*;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Assigning values to bean attributes via the properties file
    @Test
    public void setBeanByFile() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        Monster monster1000 = ("monster1000", Monster.class);
        ("monster1000=" + monster1000);
    }
}

 

Run results:

 

56, Auto Assembly Bean

 

Code Structure:

 

package ;

public class OrderDao {
    public void saveOrder() {
        ("Save an order...");
    }

}

 

package ;

import ;

public class OrderService {
    private OrderDao orderDao;

    public OrderDao getOrderDao() {
        return orderDao;
    }
    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

}

 

package ;

import ;

public class OrderAction {
    private OrderService orderService;

    public OrderService getOrderService() {
        return orderService;
    }
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:util="/schema/util"
       xmlns:context="/schema/context"
       xsi:schemaLocation="/schema/beans /schema/beans/ /schema/util /schema/util/ /schema/context /schema/context/">
    <!--Configuring the OrderDao object-->
    <bean class="" id="orderDao"/>
    <!--Configuring the OrderService Object
        Teacher's explanation
        1. autowire="byType" means when creating orderService, assign/reference to the object properties automatically by type.
        2. for example, OrderService object has private OrderDao orderDao. 3.
        3. it will look in the container to see if there is any object of type OrderDao. 4.
        4. if there is, it will be assembled automatically, the teacher reminded that if it is assembled byType, there can not be two objects of type OrderDao in the container.
          byType, there can't be two OrderDao objects in the container.
        5. If your object has no attributes, autowire is not necessary.
        6. other analogies...

        7. If we set autowire="byName", it means autowire by name.
        8. e.g. the following autowire="byName" class=""
           1) First look at the OrderService property private OrderDao orderDao
           2) Then according to this property's setXxx() method xxx to find the object ids
           3) public void setOrderDao() will look for the object id=orderDao for auto assembly.
           4) If not, the assembly fails
-->
    <bean autowire="byType" class="" id="orderService"/>
    <!--Configure OrderAction-->
    <bean autowire="byName" class="" id="orderAction"/>

</beans>

 

package ;

import .*;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class SpringBeanTest {

    //Assigning Values to Properties via Auto Assembly
    @Test
    public void setBeanByAutowire() {
        ApplicationContext ioc =
                new ClassPathXmlApplicationContext("");
        OrderAction orderAction = ("orderAction", OrderAction.class);

        //Verify that the OrderService is automatically assembled.
        (());
        //Verify that the OrderDao is automatically assembled.
        (().getOrderDao());
    }
}

 

Run results: