Config 相关注解
@Configuration:指定当前类为配置类(注意:当配置类为AnnotationConfigApplicationContext对象创建的参数时,可不写)
@ComponentScan(value="packagename")
指定spring在创建容器时要扫描的包,等价于<context:component-scan base-package="com.kunjava"></context:component-scan>
@Bean("aliasName"):当前类中的方法的返回值作为bean对象存入SpringIOC容器中
@Import(ClassName.class):导入其他的配置类。一般含有Import注解的类为父配置类
@ImportResource("classpath:xx.xml") //导入指定xml文件的配置,classpath表示类路径下
@PropertySource("classpath:xx.properties"):导入指定properties文件位置,classpath表示类路径下
@Value("${key}"):根据properties的key获取value值
测试:Spring整合Junit
<!-- 引入spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- junit的版本必须大于4.12 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
/**
* 使用Junit单元测试,测试我们的配置
*
* Spring整合Junit的配置
* 1、导入spring整合junit的jar包
* 2、使用junit提供的一个注解把原有的main方法替换成spring提供的@Runwith
* 3、告知spring的运行器,spring和ioc的创建是基于xml还是注解,并指出位置
* @ContextConfiguration:
* locations:指定xml文件的位置,加上classpath关键字
* classes:指定注解类的所在位置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ProjectConfiguration.class)//ProjectConfiguration是我的配置类
//@ContextConfiguration(locations = "classpath:bean.xml")
public class IAccountServiceTest {
@Autowired //注入IAccountService
private IAccountService as;
@Test
public void testFindAll(){
// 注释的为原来的代码
// ApplicationContext ac = new AnnotationConfigApplicationContext(ProjectConfiguration.class);
// IAccountService as = ac.getBean("accountService",IAccountService.class);
List<Account> accounts = as.findAllAccount();
for (Account account:accounts){
System.out.println(account);
}
}
}