Spring In Action-2.1-01-@Component注解
代码下载:http://download.csdn.net/download/poiuy1991719/9959474
//@Component注解会告诉Spring创建这个类的实例bean(注意,启动Component注解功能需要在xml里面配置,下面会将)
@Component
//接口
package soundsystem; import org.springframework.stereotype.Component; public interface CompactDisc { void play(); }
//接口实现类
package soundsystem; import org.springframework.stereotype.Component; //@Component注解会告诉Spring创建这个类的实例bean(注意,启动Component注解功能需要在xml里面配置) @Component public class SgtPeppers implements CompactDisc { private String title="Pepper's Lonely"; private String artist="The beatles"; SgtPeppers(){ System.out.println("SgtPeppers类实例化"); } public void play() { System.out.println("Sgt Playing:title="+title+" artist="+artist); } }
扫描有两种方式:
一、java代码方式:
//配置类 package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; //ComponentScan:本类所在包的所有子包都会被扫描,并自动为其创建bean @Configuration @ComponentScan public class CDPlayerSpringConfig { }
//测试类
package soundsystem; import org.junit.BeforeClass; 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)//Spring的Junit测试,会在测试开始时,创建Spring的应用上下文 @ContextConfiguration(classes=CDPlayerSpringConfig.class)//表明配置类 public class SpringTest1 { //自动装配 @Autowired private SgtPeppers sp; @Test public void instanceSpring(){ sp.play(); } }
二、xml配置方式:
package soundsystem; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest2 { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring(){ //将配置传过去,实例化容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); SgtPeppers sp = (SgtPeppers)ctx.getBean("sgtPeppers"); sp.play(); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自动扫描配置 --> <context:component-scan base-package="soundsystem" /> </beans>