标签:rgs spring注解 上下 构造器 his config ges gap img
针对给接口提供哪一个具体的实现,也就是装配哪一种具体的实现bean,在Spring中提供了多种方式,主要包括3种:
package bean; public interface CD { void play(); }
package bean; import org.springframework.stereotype.Component; @Component// 该注解表示该类是一个组件类,并且spring会为这个类创建一个bean public class CD1 implements CD { @Override public void play() { System.out.println("我是CD1"); } }
package bean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("cdPlayer") //声明这个类为组件类,spring会为这个类创建一个bean,这个bean的id为“cdPlayer” public class CDPlayer { private CD cd; @Autowired //自动装配注解,spring会自动注入一个CD类 public CDPlayer(CD cd) { this.cd = cd; } public void play() { cd.play(); } }
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import bean.CDConfig; import bean.CDPlayer; public class Test { public static void main(String[] args) { ApplicationContext context=new AnnotationConfigApplicationContext(CDConfig.class); CDPlayer cdplayer=(CDPlayer)context.getBean("cdPlayer"); cdplayer.play(); } }
结果:
标签:rgs spring注解 上下 构造器 his config ges gap img
原文地址:http://www.cnblogs.com/shyroke/p/6847087.html