spring属性注入的几种方式

时间:2020-05-01

1,构造参数注入

对象代码,提供一个有参的构造方法

package com.wyzda.domain;

public class User {
    private String name;
    private String password;

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

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

xml配置文件

<bean id="user" name="user" class="com.wyzda.domain.User">
        <constructor-arg name="name" value="李白"></constructor-arg>
        <constructor-arg name="password" value="123456"></constructor-arg>
</bean>

2,通过set方法注入

package com.wyzda.domain;

public class User {
    private String name;
    private String password;

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

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

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

配置文件代码

<bean id="user" name="user" class="com.wyzda.domain.User">
        <property name="name" value="李白"></property>
        <property name="password" value="123456"></property>
</bean>

还可以用Spel方式写

<bean id="user" name="user" class="com.wyzda.domain.User">
        <property name="name" value="#{'张三'}"></property>
        <property name="password" value="#{'123456'}"></property>
</bean>

还可以用p命名空间写

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="user" name="user" class="com.wyzda.domain.User" p:name="杜甫" p:password="123"></bean>

</beans>