Spring框架

一.Spring框架的概念
  Spring是一个开源容器框架,可以接管web层,业务层,dao层,持久层的组件,并且可以配置各种bean,和维护bean与bean之间的关系。其核心就是控制反转(IOC),和面向切面(AOP),简单的说就是一个分层的轻量级开源框架。
二.Spring中的IOC
  IOC:(全称:Inverse Of Control )控制反转,容器主动将资源推送给它所管理的组件,组件所做的是选择一种合理的方式接受资源。

简单的理解:把创建对象和维护之间的关系的权利由程序中转移到Spring容器的配置文件中。

DI:(全称:Dependency Injection)依赖注入,IOC的另一种表现方式,组件以一种预先定义好的方式来接受容器注入的资源。

三.Spring框架原理

public class Person {

private String name;

private int age;

private Book book;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public Book getBook() {
    return book;
}

public void setBook(Book book) {
    this.book = book;
}
**2.建一个Book类**
public class Book {

private String name;

private int price;

private String place;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

}
applicationContext.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的配置文件 -->

    <bean id="person" class="org.jingdong.bean.life.Person">
    <property name="name" value="grl"></property>
    <property name="age" value="11"></property>
    <property name="book" ref="book"></property>
    </bean>
    <bean id="book" class="org.jingdong.bean.life.Book">
    <property name="name" value="think in java"></property>
    <property name="place" value="USA"></property>
    <property name="price" value="79"></property>
    </beans>

Main.java

public class Main {
    public static void main(String[] args) {
        // 创建IOC容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从容器中获取bean实例
        Person person = (Person) ac.getBean("person");
        //使用bean
        System.out.println(person.getName());
    }
}
(1).当ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext .xml");被执行时,Spring容器对象被创建,同时applicationContext .xml中的bean就会被创建到内存中:

在这里插入图片描述
配置bean的方式:

(1).通过ApplicationContext上下文容器:当在加载xml配置文件时,配置文件中的配置的bean已经被实例化

(2).BeanFactory:在加载配置文件时,配置文件中的bean不被实例化,只有当通过getBean(),获取bean实例的时候才被创建。

总结:通过BeanFactory配置的bean比通过ApplicationContext配置的节约内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值