spring-context基础注解开发笔记
基于spring-context基本框架的注解开发主要内容如下图
一、bean注解
1.1 基本配置
使用在自已写的类上添加@Component完成对该类定义,例子如下:
@Component
public class BookDaoImpl implements BookDao {
//to do something
}
Spring为了更方便大家区分bean的用途在Component下派生出三个子类:
- @Controller 常用于web层,比如控制器
- @Repository 常用于数据层
- @Service 常用于业务层
编写完了在xml配置文件中添加一个包扫描即可
<context:component-scan base-package="com.xxx" />
1.2 其它配置项
- @Scope 设定作用域,单例还是多例
- @PostConstruct 设定初始化函数,在构造函数后执行
- @PrevDestroy 设定销毁函数,在Spring容器销毁前执行
二、SpringContext.xml核心配置文件改造
2.1 配置类编写方式
通过编写一个类并用@Configuration方式来指定该类作为配置文件使用,例子如下:
//配置类注解(必填)
@Configuration
//包扫描路径
@ComponentScan("com.hyq")
public class SpringConfig {
}
2.2 spring容器创建
不同于xml文件方式,spring容器要用AnnotationConfigApplicationContext来实例化,代码如下:
//创建容器
ApplicationContext ctx =new AnnotationConfigApplicationContext(SpringConfig.class);
//获取Bean