分享

Spring1——初识Spring、IOC控制反转(DI:依赖注入)

 头号码甲 2020-06-13
初识Spring
1.搭建spring环境
下载jar包
https://maven./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:///tools/sts/all) springsource-tool-suite-3.9.11.RELEASE-e4.12.0-updatesite.zip。
方式二:下载sts工具
新建:applicationContext.xml
 
3.开发spring程序(IOC)
//Spring上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//执行从spring ioc容器中拿到id为student的对象
Student student = (Student) context.getBean("student");
 
 
 
IOC控制反转(DI:依赖注入)
SpringIOC发展史:
1. Student student=new Student();
  student.setxxx(x);
2.简单工厂
3.IOC(超级工厂)
 
IOC也可以成为DI(依赖注入)。
总结:ioc/di,无论要什么对象,都可以直接从spring ioc中获取,不需要自己操作。
 
IOC容器的赋值:如果是简单类型(8个基本+String),用value赋值;
                          如果是对象类型,用ref赋值,ref=需要引用的id,实现了对象与对象之间的依赖关系。
 
依赖注入的三种方式:
1.set注入
赋值,默认使用的是set方法。
依赖注入底层是通过反射实现的。
<property name="stuNo" value="1"></property>
2.构造器注入:通过构造方法赋值
<constructor-arg value="21" index="1" type="int" name="age"></constructor-arg>
3.p命名空间注入
(1)引入p命名空间:xmlns:p="http://www./schema/p"
(2)<bean id="course" class="org.ghl.entity.Course" p:courseName="jacv" p:courseHour="344" p:teacher-ref="teacher">
注意:简单类型 p:属性名=“属性值”
     引用类型 p:属性名-ref=“引用的id”
     多个p赋值之间要有空格。
 
注入各种数据集合类型:
list:
<property name="list">
<list>
<value>足球</value>
<value>篮球</value>
<value>乒乓球</value>
</list>
</property>
array:
<array>
<value>足球a</value>
<value>篮球a</value>
<value>乒乓球a</value>
</array>
set:
<set>
<value>足球s</value>
<value>篮球s</value>
<value>乒乓球s</value>
</set>
map:
<map>
<entry>
<key>
<value>foot</value>
</key>
<value>足球m</value>
</entry>
</map>
properties:
<props>
<prop key="footp">足球p</prop>
<prop key="baskp">篮球p</prop>
<prop key="ppp">乒乓球p</prop>
</props>
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约