一、基于spring framework框架开发的项目,为了测试项目,需要对spring框架有基础了解
- Spring是一个非常活跃的开源框架,由Rod Johnson开发
- 帮助分离项目组件之间的依赖关系
- 主要目的:简化企业开发
二、核心概念
- IoC:Inversion of Control 控制反转
- DI:Dependency Injection 依赖注入
- AOP:Aspect Oriented Programming 面向切面编程
三、Spring Framework Runtime
重点介绍:
核心模块:Core Container
core:Ioc,DI
Beans: bean的装配,可以理解为对象的创建
SpEL:spring的表达式语言
数据访问层
- 对JDBC的封装
- ORM:封装了持久层框架的代码,如Hibernate
- OXM:xml和对象映射的支持,可以让对象和xml相互转换
- Transations: 事务管理
Test:Spring提供的测试功能(待单独开篇)
实践之IOC&DI
- xml和注解方式的IOC和DI
- 注解方式:
`@Autowired
public void setService(MessageService service) {
this.service = service;
}
@ComponentScan
public class ApplicationSpring {
public static void main(String[] args){
System.out.println("applicationSpring");
//基于注解的方式初始化spring的容器
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationSpring.class);`
- xml方式
去除类中的类名和方法的注解
<bean id="servcie" class="hello.MessageService"></bean>
<!--相当于把MessagaeService对象service成功注入到MessagePrinter中-->
<bean id="printer" class="hello.MessagePrinter">
<property name="service" ref="servcie"></property>
</bean>
- 使用配置类
@Configuration
@ComponentScan
public class AppConfig {
}
main方法中去掉注解ComponeScan并把上下文切到配置类中
//@ComponentScan
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
总结:自动装配
-
组件扫描
- @Component:表示这个类需要在应用程序中创建
- @ComponentScan:自动发现应用程序中已经创建的类
-
自动装配
- @Autowired:自动满足bean之间关系依赖
-
定义配置类
- @Configuration:表示当前类是一个配置类
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。