Spring IOC(一)

介绍

IOC,inversion of control,控制反转。经典的,我们用关键字new去主动创建对象。而将创建对象的功能交给容器,再根据需要获取就称为控制反转。这里的容器称为IOC容器。

简单案例

1、pom.xml

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.1.9.RELEASE</version>
</dependency>

自spring5起,需要jdk8+的支持

2、bean类

public class Student{
      private String name;
      private String className;
      private Integer age;
      private Date now;//假设为当前时间
      //getter和setter方法省略
}

3、spring配置文件: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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.tj.entity.User"></bean>
</beans>
  • id:唯一标识符,如果不配的话,会以类名的首字母小写作为id
  • class:类的全路径名

4、使用

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//Student student = (Student) applicationContext.getBean("student");
Student student = applicationContext.getBean("student",Student.class);

容器

  • BeanFactory:基本的bean对象管理
  • XmlBeanFactory:BeanFactory的重要实现类
  • ApplicationContext:BeanFactory的子接口,提供了企业级的支持
  • WebXmlApplicationContext:用于网络加载,在springmvc框架内部有用到,但一般不会直接配置
  • FileSystemXmlApplicationContext:构造方法参数为spring配置文件的系统路径,配置麻烦,不方便项目迁移
  • ClassPathXmlApplicationContext:构造方法参数为spring配置文件相对项目根目录的路径,配置简单,迁移方便

作用域范围

  • singleton:单例,在容器加载时创建。当应用结束,容器销毁时被销毁。
  • prototype:多例,每次请求时创建,对象使用结束时销毁。
  • request:单次请求
  • session:一次会话
  • global-session:集群下的session

多配置文件加载

1、在创建IOC容器时,在构造方法里传入多个配置文件路径参数

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

2、在一个配置文件中,导入其它配置文件

<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

属性文件加载

https://www.jb51.net/article/140459.htm
总的有四种方案,常用这两种
1、单文件加载(只能单文件)

<context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties"/>

<property name="url" value="${jdbc.url}" /> 
<property name="username" value="${jdbc.username}" /> 
<property name="password" value="${jdbc.password}" />

2、多文件加载(也可以单文件)

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
        <list> 
            <value>classpath:redis-key.properties</value> 
        </list> 
    </property> 
</bean> 
原文地址:https://www.cnblogs.com/heibaimao123/p/13792777.html