[关闭]
@Cesar 2015-12-27T21:11:33.000000Z 字数 1518 阅读 1617

Spring中三种注入方式

spring 学习


目录

  1. 构造器注入
  2. 工厂方法注入
  3. setter注入

1.构造器注入

xml:

  1. <bean id="duke" class="cesar.test.spring.bean.Judgler">
  2. <constructor-arg value="15"></constructor-arg>
  3. </bean>

java:

  1. public class Judgler implements Performer{
  2. private int beanBags = 3;
  3. public Judgler(){
  4. }
  5. Judgler(int beanBags){
  6. this.beanBags = beanBags;
  7. }
  8. @Override
  9. public void perform() {
  10. System.out.println("JUGGLING "+ beanBags+" BEANBAGS");
  11. }
  12. }

2.setter注入

java文件:

  1. package cesar.test.spring.bean;
  2. import cesar.test.spring.Instrument;
  3. public class Instrumentalist implements Performer {
  4. public Instrumentalist() {
  5. }
  6. private String song;
  7. private Instrument instrument;
  8. public void setSong(String song) {
  9. this.song = song;
  10. }
  11. public String getSong() {
  12. return song;
  13. }
  14. @Override
  15. public void perform() {
  16. System.out.println("playing"+song+":");
  17. instrument.play();
  18. }
  19. public Instrument getInstrument() {
  20. return instrument;
  21. }
  22. public void setInstrument(Instrument instrument) {
  23. this.instrument = instrument;
  24. }
  25. }

2.1 注入简单值

  1. <bean id="instru" class="cesar.test.spring.bean.Instrumentalist">
  2. <property name="song" value="我恨我爱你"></property>
  3. </bean>

2.2 注入其他bean

  1. <bean id="instru" class="cesar.test.spring.bean.Instrumentalist">
  2. <property name="song" value="我恨我爱你"></property>
  3. <property name="instrument" ref=""></property>
  4. </bean>

3.工厂方法注入

xml:

  1. <bean id="theStage" class="cesar.test.spring.bean.Stage"
  2. factory-method="getInstance">
  3. </bean>

java:

  1. public class Stage {
  2. private Stage(){}
  3. private static class StageSingletonHolder{
  4. static Stage instance = new Stage();
  5. }
  6. public static Stage getInstance(){
  7. return StageSingletonHolder.instance;
  8. }
  9. public void sayHello() {
  10. System.out.println("Hello");
  11. }
  12. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注