Spring简介&入门

来源:互联网 发布:acm fellow知乎 编辑:程序博客网 时间:2024/05/21 14:09

资源下载

导入相关jar包

commons-logging-1.1.3.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-context-support-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar

编写spring配置文件(名称可以自定义)

beans.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就是java对象 由spring容器来创建和管理 -->    <bean name="hello" class="com.bjsxt.bean.Hello">        <property name="name" value="spring"></property>    </bean></beans>

编写bean-pojo类

public class Hello {    private String name;    public void setName(String name) {        this.name = name;    }    public void show() {        System.out.println("hello " + name);    }}

测试:

public class HelloTest {    @Test    public void test() {        //解析beans.xml文件 生成管理相应的bean对象        //BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        Hello hello = (Hello) ac.getBean("hello");        hello.show();    }}

思考?
Hello对象是谁创建的?
Hello对象是由spring容器创建的。
Hello对象的属性是怎么设置的?
Hello对象属性是由spring容器来设置的。
这个过程就叫控制反转。
控制的内容:指谁来控制对象的创建;传统的应用程序对象的创建是由程序本身控制,使用spring以后是由spring来控制对象的创建。
反转:由主动创建变为被动接收,权限转移,角色反转。
总结:以前对象是由程序本身来创建,使用spring后程序变为被动接收spring创建好的对象。控制反转–依赖注入(Dependency Injection)
Ioc–是一种编程思想,由主动编程变为被动接收
Ioc的实现是通过ioc容器来实现的。Ioc容器-BeanFactory

0 0