Spring入门(三)
测试Spring Bean的自动化装配
方式一:使用配置文件方式启动组件扫描
准备一个接口
package soundsystem; public interface CompactDisc { void play(); }
实现准备的接口,使用@Component注解(让Spring容器发现,以创建该类实例)
package soundsystem; import org.springframework.stereotype.Component; @Component // 该注解作用:让该类作为组件类,并告知spring为这个类创建bean public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles";
public void play() { System.out.println("Playing " + title + " by " + artist); } }
在上述实现类下创建一个java文件,用@ComponentScan注解标注(默认扫描该java文件所在的包及其子包),并且用Configuration注解()
package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration public class CDPlayerConfig { }
配置文件
<?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>
测试:用SpringTest,加入jar包,在类文件中注入接口实现类,用@Autowired注解(将该注解指定的bean注入进该实例中使用),类文件上使用@RunWith注解,@ConfigurationContext注解
package soundsystem; 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(locations="classpath:applicationContext.xml") public class CDPlayerTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); cd.play(); } }
方式二:用注解方式启动组件扫描
创建接口与创建接口的实现类方法相同,此处不再赘述
java文件
package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan // 启动组件扫描,扫描与配置类相同的包 public class CDPlayerConfig { }
测试文件
package soundsystem; 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)//需要在CDPlayerConfig中加載配置 public class CDPlayerTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); cd.play(); } }
@RunWith:参考https://www.jianshu.com/p/70aee958e980