Spring 基于注解的IOC配置&整合Junit
来源:互联网 发布:测试耳机的软件 编辑:程序博客网 时间:2024/06/05 05:18
基于注解的IOC配置:
共有两种:纯注解配置、依赖于xml文件中context标签的配置。
依赖于xml文件中context标签:
配置方法:在spring的配置文件中开启spring对注解ioc的支持
<!-- 告知spring框架在,读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 --> <context:component-scan base-package="要扫描的包"></context:component-scan>
获取容器:
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
纯注解配置:
可以完全脱离xml文件
配置方法:在一个类上编写两个标签。
@Configuration//表明当前类是一个配置类@ComponentScan(basePackages = "配置要扫描的包")
获取容器:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);//参数为类的字节码文件
新注解说明:
@Bean
作用:
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。它就相当于之前在xml配置中介绍的factory-bean和factory-method。
属性:
name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。
@PropertySource
作用:
用于加载.properties文件中的配置。例如配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。
属性:
value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
@Import
作用:
用于导入其他配置类。
属性:
value[]:用于指定其他配置类的字节码。
两种配置方式常用注解:
@Component
用于创建对象的
相当于:<bean id="" class="">
有三个衍生注解:
@Controller:一般用于表现层的注解。
@Service:一般用于业务层的注解。
@Repository:一般用于持久层的注解。
@Autowird
自动按照类型注入。set方法可以省略。是注入引用类型数据的。
相当于:<property name="" ref="">
@Value
注入基本数据类型和String类型数据的
相当于:<property name="" value="">
@Scope
指定Bean的作用范围
相当于:<bean id="" class="" scope="">
和生命周期相关的两个注解
相当于:
<bean id="" class="" init-method="" destroy-method="" />
@PostConstruct
作用:
用于指定初始化方法。
@PreDestroy
作用:
用于指定销毁方法。
Spring整合Junit:
引入spring-test jar包
用法:
@RunWith(SpringJUnit4ClassRunner.class) //注解替换原有运行器(spring中的容器,也就是把创建容器的代码封装了起来) @ContextConfiguration("classpath:applicationContext.xml")//指定spring配置文件的位置(传参的作用)
如果是纯注解配置的话:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes={纯注解的类的字节码文件.class})
注:整合junit是基于junit的,只有编译运行@Test,整合的注解才会执行替换原有的运行器。
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")//这两个注解才会运行
- Spring 基于注解的IOC配置&整合Junit
- Spring 基于注解的IOC配置
- Spring教程--IOC(注解方式)和整合junit
- 基于注解的IOC配置
- 【Spring】IOC之基于注解的配置bean(上)
- 基于spring 3 注解的junit测试
- Spring IOC 基于注解的使用
- Spring--IoC--基于注解的DI-@Scope
- Spring IoC 注解配置
- Spring IoC 注解配置
- (spring-第4回【IoC基础篇】)spring基于注解的配置
- Spring框架总结——第二部分(基于xml配置+注解的方式配置IOC)
- 通过注解方式配置Spring的IoC
- spring的配置及ioc注解总结
- Spring--IoC--基于注解的DI-@Component相关注解
- Spring框架整合Junit单元测试框架的纯注解方式
- 【Java.Spring.Core】【IoC】基于注解的Bean装配(非XML配置)
- Spring与hibernate的整合(基于注解
- Kali linux搭建wifi绵羊墙
- Redis的常用方法总结
- 51nod 1607-卷积和(数位DP)
- Linux下33个常用的Find实例
- oracle连表查询
- Spring 基于注解的IOC配置&整合Junit
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- JavaScript版正则表达式组合和限制字符
- SCU
- Struts2创建项目3--Struts2传值
- DP算法之—Longest Common Subsequence
- HDU 6140 Hybrid Crystals【题意】【思维】
- #426 (Div. 2) B. The Festive Evening
- Object.prototype.toString.call()方法浅谈