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")//这两个注解才会运行
原创粉丝点击