本篇文章讲解了Spring的通过内部Bean设置Bean的属性

  类似内部类,内部Bean与普通的Bean关联不同的是:

  1 普通的Bean,在其他的Bean实例引用时,都引用同一个实例。

  2 内部Bean,每次引用时都是新创建的实例。

  鉴于上述的场景,内部Bean是一个很常用的编程模式。

  下面先通过前文所述的表演者的例子,描述一下主要的类:

package com.spring.test.setter;

import com.spring.test.action1.PerformanceException;
import com.spring.test.action1.Performer;

public class Instrumentalist implements Performer{
    private String song;
    private int age;
    private Instrument instrument;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSong() {
        return song;
    }
    public void setSong(String song) {
        this.song = song;
    }
    public Instrument getInstrument() {
        return instrument;
    }
    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }
    public Instrumentalist(){}
    public Instrumentalist(String song,int age,Instrument instrument){
        this.song = song;
        this.age = age;
        this.instrument = instrument;
    }
    public void perform() throws PerformanceException {
        System.out.println("Instrumentalist age:"+age);
        System.out.print("Playing "+song+":");
        instrument.play();
    }
}

  其他代码,如下:

package com.spring.test.setter;

public interface Instrument {
    public void play();
}
View Code

相关文章:

  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2021-07-23
  • 2021-08-21
  • 2021-07-02
  • 2021-07-01
  • 2022-01-23
猜你喜欢
  • 2021-12-28
  • 2021-11-29
  • 2021-05-31
  • 2021-06-11
  • 2021-05-17
  • 2021-05-04
  • 2022-01-15
相关资源
相似解决方案