Spring基础概念

1.控制反转(Inversion of Control)

程序使用对象时,由主动new产生对象转换为由IoC容器提供对象,对象的创建控制权由程序转移到Ioc容器

2.依赖注入(Dependency Injection)

在IoC容器中建立Bean与Bean之间的依赖关系的整个过程称为依赖注入

3.面向切面编程(Aspect Oriented Programming)

功能的横向抽取,主要的实现方式就是Proxy

4.Bean

Ioc容器负责对象的创建、初始化等一系列工作,被创建或被管理的对象在Ioc容器中统称为Bean

5.IOC和DI入门案例

(1)在Maven项目中加入Spring的依赖坐标

<dependency>
	<groupId>org.springframeworkgroupId>
	<artifactId>spring-contextartifactId>
	<version>5.1.0.RELEASEversion>
dependency>

(2)创建applicationContext.xml文件定义Bean并定义依赖关系


<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="animal" class="Animal">
        
        <property name="people" ref="people"/>
        <property name="name" value="猫咪"/>
        <property name="age" value="2"/>
        <property name="eat" value="睡觉"/>
    bean>
    <bean id="people" class="People">
        <property name="name" value="张三"/>
        <property name="age" value="18"/>
        <property name="eat" value="吃饭"/>
    bean>
beans>

(3)获取容器,获取bean

public class Demo {
    public static void main(String[] args) {
        //获取IoC容器
        ApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");
        //获取Bean
        Animal animal = (Animal) ctx.getBean("animal");
        People people = (People) ctx.getBean("people");
        System.out.println(animal);
        System.out.println(people);

    }
}

6.Bean的配置

(1)Bean的定义
使用标签定义bean,id属性表示bean在容器中的唯一标识,class属性表示bean的全路径类名
(2)Bean的别名
标签的name属性表示bean的别名,可以定义多个,使用逗号、分好、空格分隔

	<bean id="people" name = "people1 people2" class="People">
        <property name="name" value="张三"/>
        <property name="age" value="18"/>
        <property name="eat" value="吃饭"/>
    bean>

注:获取bean无论是通过id还是name获取,如果无法获取到,将抛出NoSuchBeanDefinitionException异常
(3)Bean的作用范围
标签的scope属性表示bean的作用范围(即是单例的还是多例的),singleton:单例;prototype:多例

	<bean id="animal" class="Animal" scope="singleton">
        <property name="people" ref="people"/>
        <property name="name" value="猫咪"/>
        <property name="age" value="2"/>
        <property name="eat" value="睡觉"/>
    bean>
    <bean id="people" class="People" scope="prototype">
        <property name="name" value="张三"/>
        <property name="age" value="18"/>
        <property name="eat" value="吃饭"/>
    bean>

注:适合交给容器管理的bean:表现层对象、业务层对象、数据层对象、工具对象。不适合交给容器进行管理的bean:封装实体的域对象

你可能感兴趣的:(Spring,spring,java,后端)