spring属性的三种注入方法

Posted xiaoxiaoの

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring属性的三种注入方法相关的知识,希望对你有一定的参考价值。

(1)使用set方法:

public class Book {
  private String bookname;
public void setBookname(String bookname) {
    this.bookname = bookname;
}

xml配置:

<bean id="book" class="com.example.propetys.Book">
<!-- 注入属性值 name属性:值是你定义的属性的名称,value属性:设置的具体的值 -->
<property name="bookname" value="九阳真经"></property>
</bean>

(2)有参数的构造

public class PropertDemo1 {
    private String username;
    public PropertDemo1(String username) {
        this.username = username;
    }

xml配置:

<bean id="demo" class="com.example.propetys.PropertDemo1">
<!-- 有参构造方法注入 -->
    <constructor-arg name="username" value="liuguxiia"></constructor-arg>
 </bean>

(3)使用接口注入

public Interface Dao{

  public void delete(String name);

}

public class DaoImpl implements Dao{

   private String name;

   public void delete(String name){

       this.name=name;

      }

}

在spring框架里,只允许前两种方式。















以上是关于spring属性的三种注入方法的主要内容,如果未能解决你的问题,请参考以下文章

Spring中@Value的三种使用方式

Spring依赖注入(DI)的三种方式

扯一把 Spring 的三种注入方式,到底哪种注入方式最佳?

扯一把 Spring 的三种注入方式,到底哪种注入方式最佳?

spring 装配bean的三种方式

Spring5依赖注入常用的三种方法:构造注入Setter注入自动装配