标签:定义 体会 sse 分享 private span run 注解 one
1 package com.spring.cd; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Component; 5 6 @Component//Spring自动创建bean 7 public class CDPlayer implements MediaPlayer{ 8 private CompactDisc cd; 9 10 @Autowired//表明Spring初始化后尽可能地去满足bean的依赖,在这里它注入了一个CompactDisc的对象 11 public CDPlayer(CompactDisc cd){ 12 this.cd=cd; 13 } 14 @Override 15 public void player() { 16 System.out.println("wo yong CD!"); 17 } 18 }
当然,我们也可以在创建bean时对它命名,在CDPlayer类中可以体会到。代码如下:
package com.spring.cd; import org.springframework.stereotype.Component; @Component("ZhouJieLun") public class CompactDisc_zhoujielun implements CompactDisc{ private String title="发如雪"; private String artist="周杰伦"; @Override public void play(){ System.out.println("播放:"+title+"来自艺术家:"+artist); } }
package com.spring.cd; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan("com.spring.cd") //参数代表当前需要扫描的路径,为空默认为当前包路径 @Configuration("cd")//需要扫描的包名称 //通过java代码定义spring的装配机制 public class CDPlayerConfig { }
值得注意的是,真正的实现过程与代码主体非常复杂,@Component,@ComponScan,@Autowired,@Comfiguration等注解的使用方法与参数是多样的。
package com.spring.cd; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=CDPlayerConfig.class) public class CDPlayerTest{ @Autowired private CompactDisc cd; @Autowired private MediaPlayer player; @Test public void test() { player.player(); cd.play(); assertNotNull(cd); assertNotNull(player); } }
热爱分享拒绝拿来主义,博客精神永存——cvrigo
2016-11-09 00:19:44
标签:定义 体会 sse 分享 private span run 注解 one
原文地址:http://www.cnblogs.com/cvirgo/p/6045368.html