名词
初学会接触到的一些名词:
- 容器(Container):管理对象的生成,资源的取得,销毁等生命周期。
- 控制反转(Inversion of Control 简称:IOC):核心概念。控制反转(Inversion of Control 简称:IOC):核心概念。在Spring中,“依赖关系的转移”,“依赖于抽象而非实战”重要概念。
- 高层模块不应该依赖低层模块,模块必须依赖于抽象
- 实现必须依赖抽象,而抽象不是依赖实现
- 应用程序不应该依赖容器,而是容器服务于应用程序
- 依赖注入(Dependency Injection 简称:DI)
- 程序不依赖实现,程序实现依赖抽象。
- 分类:
- (1)Type 1 Ioc:必须实现IDependency接口,并让容器来管理对象,容器会执行createDependency()方法来建立依赖关系。
- (2)Type 2 Ioc:通过Setter(set方法)注入所依赖的对象。
- (3)Type 3 Ioc:在构造函数的时候注入依赖对象。
- AOP:Spring支持的一个框架
** 下载 **
- doc文件夹目录下主要是一些API文档
- lib文件夹目录下是依赖所需要的包
- schema文件夹下是一些xsd文件
- 链接2
两个文件- spring-framework-版本号-with-dependencies.zip:会包括其他java项目的依赖包,推荐使用。
- —spring.jar加入这个就不需要其他spring的jar包了
- —spring-core.jar:核心包
- —spring-bean.jar
- spring-framework-版本 -.zip:如果有相关文件,下这个就好了。
第一个程序HelloWorld
环境准备
1.需要的jar包:
- spring-core.jar
- spring-bean.jar
- spring-context.jar
- commons-logging.jar
- log4j.jar :设置日志
将这些jar导入程序
2.编写程序
第一个组件,一个简单的javabean
public class HelloBean {
private String helloword;
public String getHelloword() {
return helloword;
}
//通过这个来设置(注入文字Type 2 Ioc)
public void setHelloword(String helloword) {
this.helloword = helloword;
}
}
bean-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloBean"
class="com.hello.HelloBean"
>
<property name="helloword" >
<value>你好呀!</value>
</property>
</bean>
</beans>
第一种写法:
SpringDemo1.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SpringDemo1 {
public static void main(String[] args) {
Resource rs=new ClassPathResource("bean-config.xml");//获取xml配置文件
BeanFactory beanFactory=new XmlBeanFactory(rs);//Bean的工厂
HelloBean helloBean= (HelloBean) beanFactory.getBean("helloBean");//注入
System.out.println(helloBean.getHelloword());
}
}
第二种写法:
SpringDemo2.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo2 {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean-config.xml");//获取xml配置文件
HelloBean helloBean= (HelloBean) applicationContext.getBean("helloBean");//注入
System.out.println(helloBean.getHelloword());
}
}
两者的运行结果是一样的。