[spring object creation method] and [Java object creation method]

How to create objects in Spring

Create objects through constructors, create objects through static factories, and create objects through instance factories

1. Create objects through constructors

No-argument constructor:
the most basic method of object creation, only need to have a no-argument constructor (no constructor is written in the class, there is a default constructor, if any constructor is written, the default no-argument constructor The function will not be created automatically!!) and the setter method of the field.

1.1 Entity class User object:

package com.java.entity;

public class User {
    
    
    public User() {
    
    
        System.err.println("空参构造方法!");
    }

    private String name;
    private Integer password;
    private String dir;
    private Integer age;

    public String getName() {
    
    
        return name;
    }

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

    public Integer getPassword() {
    
    
        return password;
    }

    public void setPassword(Integer password) {
    
    
        this.password = password;
    }

    public String getDir() {
    
    
        return dir;
    }

    public void setDir(String dir) {
    
    
        this.dir = dir;
    }

    public Integer getAge() {
    
    
        return age;
    }

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

    @Override
    public String toString() {
    
    
        return "user [name=" + name + ", password=" + password + ", dir=" + dir + ", age=" + age + "]";
    }
}

1.2 Core configuration file: applicationContext.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
    <!-- 创建对象方式一:空参构造 -->
    <bean name="user" class="com.java.entity.User"></bean>
</beans>

1.3 Test class:

@Test
// 空参构造创建对象的方式
public void test1(){
    
    
    // 加载核心配置文件  --- 此步中applicationContext会直接将所有的实体类创建出来;
     ApplicationContext c=new ClassPathXmlApplicationContext("applicationContext.xml");
     User user=(User)c.getBean("user");
     System.out.println(user);
}

insert image description here

If the test method:

User user=(User)c.getBean("user");
System.out.println(user);

If these two lines are blocked (or removed), there will still be a prompt to print out the empty parameter call in the entity class, because the ApplicationContext will create all the objects under its jurisdiction once the container is loaded;

Create an object with a parameterized constructor: (create an object with initialized data)

Entity class:

package com.wshy.pojo;

/**
 * @title: User
 * @Author: wshy
 */
public class User {
    
    
    private String name;

    private int age;

    private String address;

    //public User () {
    
    
    //    System.out.println ("Spring-User无参构造函数!");
    //}

    public User (String name) {
    
    
        System.out.println ("Spring-User有参构造函数!");
        this.name = name;
    }

    public String getName () {
    
    
        return name;
    }

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

    public int getAge () {
    
    
        return age;
    }

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

    public String getAddress () {
    
    
        return address;
    }

    public void setAddress (String address) {
    
    
        this.address = address;
    }
}

Create objects using subscript assignment:

<bean id="user" class="com.wshy.spring.User">
    <constructor-arg index="0" value="wshy"/>
</bean>

constructor-arg tag: Create an object according to the subscript assignment. At this time, index=0 means to assign a value to the first field value in the User entity class table, and value means to display the value

Create an object with a type:

<bean id="user" class="com.wshy.spring.User">
    <constructor-arg type="java.lang.String" value="wshy"/>
</bean>

constructor-arg tag: Create an object according to the type type. At this time, index="java.lang.String" indicates that the input parameter of the User parameter constructor assigns a value to a String type field and creates an object. Value indicates the display value, but at this time , if there are multiple input parameters in the parameter constructor, and all of them are of String type, there will be limitations in creating objects according to the type!
insert image description here

Create an object with parameters

<!--
constructor-arg标签:根据type类型创建对象,name为传入参数,value指定参数传入值
-->
<bean id="user" class="com.wshy.pojo.User">
    <constructor-arg name="name" value="根据参数创建对象"/>
</bean>

2. Create an object through a static factory method, and there is a static factory method corresponding to the entity

2.1 The entity class object is the same as the entity class object in the object created by the constructor
2.2 The static factory method for creating objects: UserFactory.java User factory

package com.java.Factory;
import com.java.entity.User;

public class UserFactory {
    
    

    public static User crivateUser() {
    
    
        System.out.println("静态工厂构造对象!");
        User user = new User();
        return user;
    }
}

2.3 Core configuration file: ApplicationContext.xml core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
    <!-- 创建对象方式二:静态工厂构造 -->
    <bean name="user2" class="com.java.Factory.UserFactory" factory-method="crivateUser"></bean>
</beans>

The attribute value of the class attribute is no longer the full path of the entity object, but the full path of the static factory of the entity object; secondly, there is an additional attribute, and this attribute value is the method name for creating the entity object in the static factory;

2.4 Test class

@Test
// 静态工厂构造创建对象的方式
public void test2(){
    
    
    ApplicationContext c=new ClassPathXmlApplicationContext("applicationContext.xml");
    User user=(User)c.getBean("user2");
    System.out.println(user);
}

insert image description here

3. Create objects through instance factories

3.1 The entity class object is the same as the entity class object in the object created by the constructor
3.2 Entity object factory: UserFactory.java User factory

package com.java.Factory;
import com.java.entity.User;

public class UserFactory {
    
    

    public  User crivateUser2() {
    
    
        System.out.println("实例工厂构造对象!");
        User user = new User();
        return user;
    }
}

3.3 Core configuration file: ApplicationContext.xml Core configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
    <!-- 创建对象方式三:实例工厂构造 -->
    <bean name="user3" factory-bean="UserFactory" factory-method="crivateUser2"></bean>
    <bean name="UserFactory" class="com.java.Factory.UserFactory"></bean>
</beans>

Because the dynamic (instance) method call is used, the configuration of the method name is different from that of the static factory. The factory name (UserFactory) and method name (crivateUser2) of the dynamic (instance) factory to be called need to be first Write it out in the first Bean element, and then configure the full path of the factory name in the second Bean element according to the factory name (UserFactory);

3.4 Test method

@Test
// 实例工厂构造创建对象的方式
public void test3(){
    
    
    ApplicationContext c = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) c.getBean("user3");
    System.out.println(user);
}

insert image description here

How to create objects in Java

There are six common ways to create objects in Java, namely using the new keyword, Class's newInstance() method, Constructor's newInstance() method, clone() method, deserialization, factory mode, etc.

1. Use the new keyword

The most common way to create objects in Java. The new keyword instantiates an object by calling the constructor of the class.

public class Person {
    
    
    String name;
    int age;
    
    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

Person person = new Person("小明", 18);

2. Reflection: use the newInstance() method of the Class class (the class distributes an object)

Creates a new instance of a class at runtime. It is equivalent to using the new operator, but the syntax is more dynamic.

public class Person {
    
    
    String name;
    int age;
    
    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

try {
    
    
    Person person = Person.class.newInstance();
    person.name = "小明";
    person.age = 18;
} catch (Exception e) {
    
    
    e.printStackTrace();
}

3. Reflection: use Constructor's newInstance() method to construct an object

This method can create a new instance of a class at runtime, and can pass in the parameters of the constructor. This method is more flexible than Class's newInstance() method, because you can choose different constructors.

public class Person {
    
    
    String name;
    int age;
    
    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

try {
    
    
    Constructor<Person> constructor = Person.class.getConstructor(String.class, int.class);
    Person person = constructor.newInstance("小明", 18);
} catch (Exception e) {
    
    
    e.printStackTrace();
}

4. Use the clone() method

Whenever we call the clone method of an object, the JVM will create a new object, copy all the contents of the previous object into it, and create an object with the clone method without calling any constructor. The advantage of using cloning is that you can quickly create an object with the same value as the original object, with the same field values, but two different "references".

Shallow copy only clones the fields of the basic type, and the reference type needs to rewrite the clone() method to manually assign the value of the reference field.

public class Person implements Cloneable {
    
    
    String name;
    int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
    
    
        return super.clone();
    }
}

Person person = new Person("小明", 18);
Person clone = null;
try {
    
    
    clone = (Person) person.clone();
} catch (CloneNotSupportedException e) {
    
    
    e.printStackTrace();
}

5. Use deserialization

Deserialization is the process of recovering an object from a byte stream. After serialization, the object can be stored in a file or network, and then restored into an object by deserialization.

When we serialize and deserialize an object, JVM will create a separate object for us. When deserializing, the JVM creates the object and does not call any constructors.

public class Person implements Serializable {
    
    
    String name;
    int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

Person person = new Person("小明", 18);

try {
    
    
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"));
    oos.writeObject(person);
    oos.close();
    
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
    Person clone = (Person) ois.readObject();
    ois.close();
} catch (Exception e) {
    
    
    e.printStackTrace();
}

6. Use the factory pattern

The factory pattern can decouple the creation and use of objects. Objects can be generated more flexibly by defining an object factory.

public interface Animal {
    
    
    String getName();
}

public class Cat implements Animal {
    
    
    @Override
    public String getName() {
    
    
        return "Cat";
    }
}

public class Dog implements Animal {
    
    
    @Override
    public String getName() {
    
    
        return "Dog";
    }
}

public class AnimalFactory {
    
    
    public Animal createAnimal(String type) {
    
    
        switch (type) {
    
    
            case "Cat":
                return new Cat();
            case "Dog":
                return new Dog();
            default:
                throw new IllegalArgumentException("Unsupported animal type: " + type);
        }
    }
}

AnimalFactory factory = new AnimalFactory();
Animal cat = factory.createAnimal("Cat");
Animal dog = factory.createAnimal("Dog");

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/131582625