使用ioc来创建对象有三种方式

通过无参构造方法来创建

User.java

public class Hello {
    private String name;

    public Hello() {
        System.out.println("hello的无参构造方法");
    }

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

beans.xml

    name="hello" class="com.zfy.bean.Hello">
        <property name="name" value="spring">property>
    

通过有参构造方法来创建

public class Hello {
    private String name;

    public Hello(String name) {
        this.name = name;
    }

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

beans.xml
第一种 根据参数的下标来设置

    <bean id="hello" class="com.zfy.bean.Hello">
        
        <constructor-arg index="0" value="张三">constructor-arg>
    bean>

第二种 根据参数名称来设置

    <bean id="hello" class="com.zfy.bean.Hello">
        
        <constructor-arg name="name" value="李四">constructor-arg>
    bean>

第三种 根据参数类型来设置

    <bean id="hello" class="com.zfy.bean.Hello">
        
        <constructor-arg type="java.lang.String" value="Dylan">constructor-arg>
    bean>

通过工厂方法来创建

静态工厂

public class UserStaticFactory {
    public static User newInstance(String name) {
        return new User(name);
    }
}
    <bean id="user" class="com.zfy.factory.UserStaticFactory" factory-method="newInstance">
        <constructor-arg index="0" value="张三">constructor-arg>
    bean>

动态工厂

public class UserDyanmicFactory {
    public User newInstance(String name) {
        return new User(name);
    }
}
    <bean id="userFactory" class="com.zfy.factory.UserDyanmicFactory">bean>
    <bean id="user" factory-bean="userFactory" factory-method="newInstance">
        <constructor-arg index="0" value="李四">constructor-arg>
    bean>

你可能感兴趣的:(Java)