spring初次学习,记录简单操作
2002 Rod Johnon
Spring 2003 ,IOC Aop
Spring data,spring boot,spring cloud,spring framework ,spring social
IOC :控制反转 (DI:依赖注入)
1.搭建Spring环境
下载jar
http://maven.springframework.org/release/org/springframework/spring/
spring-framework-4.3.9.RELEASE-dist.zip
开发spring至少需要使用的jar(5个+1个):
spring-aop.jar 开发AOP特性时需要的JAR
spring-beans.jar 处理Bean的jar
spring-context.jar 处理spring上下文的jar
spring-core.jar spring核心jar
spring-expression.jar spring表达式
三方提供的日志jar
commons-logging.jar 日志
2.编写配置文件
为了编写时有一些提示、自动生成一些配置信息:
方式一:增加sts插件
可以给eclipse增加 支持spring的插件:spring tool suite(https://spring.io/tools/sts/all)
下载springsource-tool-suite-3.9.4.RELEASE-e4.7.3a-updatesite.zip,然后在Eclipse中安装:Help-Install new SoftWare.. - Add
方式二:
直接下载sts工具(相当于一个集合了Spring tool suite的Eclipse): https://spring.io/tools/sts/
新建:bean configuration .. - applicationContext.xml
3.开发Spring程序(IOC)
ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
//执行从springIOC容器中获取一个 id为student的对象
Student student = (Student)conext.getBean("student") ;
可以发现,springioc容器 帮我们new了对象,并且给对象赋了值
SpringIOC发展史:
1.
Student student = new Student();
student.setXxx();
缺点每次使用对象都要new
简单工厂
3.ioc (超级工厂)
IOC(控制反转)也可以称之为DI(依赖注入):
控制反转:将 创建对象、属性值 的方式 进行了翻转,从new、setXxx() 翻转为了 从springIOC容器getBean()
依赖注入:将属性值 注入给了属性,将属性 注入给了bean,将bean注入给了ioc容器;
总结:ioc/di ,无论要什么对象,都可以直接去springioc容器中获取,而不需要自己操作(new\setXxx())
因此之后的ioc分为2步:1 先给springioc中存放对象并赋值 2 拿
DI:依赖注入 ,
Teacher
Course : cname teacher
IOC容器赋值:如果是简单类型(8个基本+String),value;
如果是对象类型,ref="需吃要引用的id值",因此实现了 对象与对象之间的依赖关系
conext.getBean(需要获取的bean的id值)
依赖注入3种方式:
1.set注入:通过setXxx()赋值
赋值,默认使用的是 set方法();
依赖注入底层是通过反射实现的。
2.构造器注入:通过构造方法赋值
需要注意:如果
3.p命名空间注入
引入p命名空间
xmlns:p="http://www.springframework.org/schema/p"
简单类型:
p:属性名="属性值"
引用类型(除了String外):
p:属性名-ref="引用的id"
注意多个 p赋值的时候 要有空格。
注意:
无论是String还是Int/short/long,在赋值时都是 value="值" ,
因此建议 此种情况 需要配合 name\type进行区分
示例:
注入各种集合数据类型: List Set map properties
set、list、数组 各自都有自己的标签 http://www.springframework.org/schema/beans"
...
default-autowire="byName">
自动装配虽然可以减少代码量,但是会降低程序的可读性,使用时需要谨慎。
=================================================
使用注解定义bean:通过注解的形式 将bean以及相应的属性值 放入ioc容器
扫描区要在context 打上√
放多个包在后面加,
@Component细化:
dao层注解:@Repository
service层注解:@Service
控制器层注解:@Controller
看完一次