Java Learning Summary - IOC's Way to Create Objects under 065 spring

Keywords: Spring xml Java encoding

How do we usually create objects?

Parametric and non-parametric structures

Let's see how to deal with these two situations in Spring.

Create entity classes

public class User {

    private String name;
    private String sex;
    private int age;

    public User() {
        System.out.println("User Nonparametric structure of");

    public User(String name) {
        System.out.println("User Parametric structure"); = name;

    public User(String name, int age) {
        System.out.println("User PARAMETRIC STRUCTURES 2"); = name;
        this.age = age;

    public User(String name, String sex, int age) {
        System.out.println("User Parametric structure 3"); = name; = sex;
        this.age = age;

    public void setName(String name) {
        System.out.println(name+":"+System.currentTimeMillis()); = name;

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

    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +

Spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<beans xmlns=""

    Spring Configuration file
    bean Represent an object
    alias  alias
    import  Import an additional resource

    <bean id="user" class="com.kuang.pojo.User">
        <property name="name" value="qinjiang"/>

    <!--Assignment using constructor parameter Subscripts-->
    <bean id="user2" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="kuangshen"/>
        <constructor-arg index="1" value="18"/>

    <!--Assignment by name-->
    <bean id="user3" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="kuangshen3"/>
        <constructor-arg name="age" value="3"/>

    <!--Assignment by type-->
    <bean id="user4" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="kuangshen4"/>
        <constructor-arg type="java.lang.Integer" value="18"/>
        <constructor-arg type="java.lang.String" value="male"/>

Test class

public class UserTest {
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User)context.getBean("user");
        User user = new User();

    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user4");


  • Through parametric structure
    • Subscript subscript
    • By parameter name [recommendation]
    • By parameter type
  • Through parametric structure
    • The default is constructed with no parameters

Note: There must be a parametric construction method.

For more information, check out: Create a factory model

Posted by fatherlyons on Tue, 08 Oct 2019 17:46:25 -0700