spring框架
以下为作者对spring粗浅的理解,若有错误欢迎指正。
第一部分
IOC ,使用ioc 就把创建对象的控制权给了IOC容器。不需要自己再去手动的new对象。IOC负责对象的创建与销毁。IOC创建出来的对象默认是单例对象
ioc容器 管理 系统中使用的bean对象,那么bean对象又是什么呢?
可以这么说 在整个系统中 用到的所有对象都可以是bean对象。
看一下项目结构
package com.xindian.tian;
public class Boy {
private Girl girl;
void kiss()
{
girl.say();
}
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
}
package com.xindian.tian;
public class Girl {
void say()
{
System.out.println("this is girl");
}
}
package com.xindian.tian;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//加载IOC容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Boy boy = (Boy) ac.getBean("boy");
boy.kiss();
Boy g1 = (Boy) ac.getBean("boy");
//由IOC容器管理的bean对象为单例对象
System.out.println(boy);
System.out.println(g1);
}
}
搭建spring开发环境
1 创建工程引入spring依赖。(java project 就可以)
2 创建spring的配置文件(在src下 创建applicationContext.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 把boy对象交给IOC容器管理。
spring框架的配置文件,配置的就是IOC容器
id属性:创建对象的引用名
class属性:创建对象所属类的类路径
Boy boy = new Boy();
-->
<bean id="boy" class="com.xindian.tian.Boy">
<!-- 维护依赖关系,使用依赖注入
name属性: 当前girl对象依赖的对象引用名
ref: 注入给boy的对象引用名
-->
<property name="girl" ref="girl"></property>
</bean>
<bean id="girl" class="com.xindian.tian.Girl">
</bean>
</beans>
3 spring框架依赖日志处理(logging)包,在工程下需要引入日志处理的jar包。
运行结果
这样 就算是搭建完成 并且配置了简单的项目了