CompactDisc类
package soundSystem;
import org.springframework.stereotype.Component;
@Component
public class CompactDisc {
public CompactDisc() {
super();
System.out.println("compactdisc无参构造方法");
}
public void play(){
System.out.println("正在播放音乐....");
}
}
CDplay类
package soundSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CDPlayer {
private CompactDisc cd;
public CDPlayer() {
super();
System.out.println("CDPlayer无参构造方法");
}
@Autowired
public CDPlayer(CompactDisc cd) {
this.cd = cd;
System.out.println("CDPlayer有参构造方法");
}
public void play(){
cd.play();
}
}
App类
package soundSystem;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
public class App {
public static void main(String[] args){
ApplicationContext context=new AnnotationConfigApplicationContext(App.class);
CDPlayer player=context.getBean(CDPlayer.class);
player.play();
}
}
appconfig类
package soundSystem;
import org.springframework.context.annotation.ComponentScan;
//spring注解类
@ComponentScan
public class Appconfig {
}
运行结果
[INFO ] 2019-10-29 19:11:30,833 method:org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:583)
Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@880ec60: startup date [Tue Oct 29 19:11:30 CST 2019]; root of context hierarchy
[DEBUG] 2019-10-29 19:11:30,857 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
[DEBUG] 2019-10-29 19:11:30,857 method:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:449)
Creating instance of bean 'org.