其他分享
首页 > 其他分享> > spring01 ioc入门

spring01 ioc入门

作者:互联网

文章目录

1.spring基本介绍

官网:spring.io

介绍:

https://baike.baidu.com/item/spring%E6%A1%86%E6%9E%B6/2853288?fr=aladdin

技术学习途径:

官网/github/码云/博客

1.好处

1.1.IOC

1.2.AOP

1.3.与所有框架的完美集成

2.IOC与DI(重要)

Inverse of Control:控制反转

Dependency Injection:DI 依赖注入

问:ioc。答,为了解耦合,所以想到了依赖注入,di是思想,IOC是结果。di思想产生是因为项目中当某个对象,想持有另外对象的引用,需要自己new,例如controller需要service。显然这种情况会导致耦合性很强,于是就想能不能不自己new,依赖其他方式注入给我,这是依赖注入思想。spring容器就能完成这种注入,而通过这种注入方式导致的结果就是对象控制权的转移,这是控制反转ioc。

2.入门

2.1.IOC jar包介绍

Spring-core:Spring的核心工具包,spring的其它包都要用到该jar中的包

Spring-beans:包含配置文件,bean的创建等,所有jar包都需要用到

Spring-context:在上面两个jar完成基础IOC功能上提供扩展服务,此外还提供许多企业级服务的支持,有邮件服务、任务调度、JNDI定位,EJB集成、远程访问、缓存以及多种视图层框架的支持。

Spring-expression:Spring表达式语言,spel表达式,SpEL支持标准数学运算符,关系运算符,逻辑运算符,条件运算符,集合和正则表达式等:

Spring-context-support:Spring context的扩展支持,用于MVC方面,比如支持freemarker等模板引擎

2.2.maven引入jar包

 <properties>
        <spring.version>5.2.11.RELEASE</spring.version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.0</version>
        <configuration>
            <source>1.8</source> <!-- 源代码使用jdk1.8支持的特性 -->
            <target>1.8</target> <!-- 使用jvm1.8编译目标代码 -->
            <compilerArgs> <!-- 传递参数 -->
                <arg>-parameters</arg>
                <arg>-Xlint:unchecked</arg>
                <arg>-Xlint:deprecation </arg>
            </compilerArgs>
        </configuration>
    </plugin>
        </plugins>
    </build>

2.3.日志配置

1.out.println:效率不高

2.打印的描述不详细,比如:如果没有详细写打印信息,都不知道是哪个类打出来的

3.输出到文件比较麻烦,上线了以后不可能看控制台,只能把运行信息写到文件中

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.26</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.26</version>
</dependency>

在resources下面加入log4j.properties

# OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
log4j.rootCategory=DEBUG, stdout , R
#输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[cdqf] %p [%t] %C.%M(%L) | %m%n


log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=D:\\spring.log #定义日志的输出位置
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

2.4.IOC配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--id:就是spring容器为当前对象,改的唯一标识-->
        <bean id="userService" class="cn.cdqf.service.impl.UserServiceImpl"></bean>
</beans>

3.入门案例

package cn.cdqf.ioc;

import cn.cdqf.service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {

    @Test
    public void iocTest1(){
        //使用ioc容器,加载配置文件
        //根据配置文件来初始化ioc容器
        //classpath:会在当前项目resources下面去找(编译后target下面找)
        //classpath*:不仅在当前项目,也会在依赖jar包的里面找
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
        //从容器中取出来对象
        UserService userService = (UserService)classPathXmlApplicationContext.getBean("userService");
        userService.show();
        //关闭容器
        classPathXmlApplicationContext.close();
    }
}


4.bean标签属性详解

4.1.id:

对当前对象的唯一标识

44.2.Scope:

singleton:SpringIoc容器只会创建该Bean的唯一实例,所有的请求和引用都只使用这个实例,默认值

prototype 每次请求都创建一个实例

request: 在一次Http请求中,容器会返回该Bean的同一个实例,而对于不同的用户请求,会返回不同的实例。需要注意的是,该作用域仅在基于Web的Spring ApplicationContext情形下有效,以下的session和global Session也是如此

session:同上,唯一的区别是请求的作用域变为了session

global session:全局的HttpSession中

4.3.Autowire:自动装配

1、 No:即不启用自动装配。Autowire默认的值。

2、 byName:通过属性的名字的方式查找JavaBean依赖的对象并为其注入,使用Seter方法为其注入。

3、 byType:通过属性的类型查找JavaBean依赖的对象并为其注入。使用Seter方法为其注入。

4、 constructor:跟byType一样,也是通过类型查找依赖对象。与byType的区别在于它不是使用Seter方法注入,而是使用构造子注入。

5、 autodetect:在byType和constructor之间自动的选择注入方式。

6、 default:由上级标签的default-autowire属性确定。

注意:在配置bean时,标签中Autowire属性的优先级比其上级标签高,即是说,如果在上级标签中定义default-autowire属性为byName,而在中定义为byType时,Spring IoC容器会优先使用标签的配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--id:就是spring容器为当前对象,改的唯一标识-->
         <!--
                scope:指定bean是单例还是多例
                autowire:
                        byName:根据属性名称去ioc容器中取
                        byType:通过属性的类型查找JavaBean依赖的对象并为其注入。使用Seter方法为其注入。
                          如果根据接口类型注入,接口有多个实现类:
                          'cn.cdqf.dao.UserDao' available: expected single matching bean but found 2: userDao,userDao2
         -->
        <bean id="userService" class="cn.cdqf.service.impl.UserServiceImpl"
        scope="singleton" autowire="byType"></bean>

        <!--
                在把当前对象放入ioc容器中的时候 不仅根据名字放了 还根据类型放了
                而且还根据接口类型也放入了
			UserDaoImpl2:userDao接口的另外实现类

        -->
       <!-- <bean id="userDao" class="cn.cdqf.dao.UserDaoImpl"></bean>-->
        <bean id="userDao2" class="cn.cdqf.dao.UserDaoImpl2"></bean>
</beans>

4.4.Factory-bean/factory-method 工厂方法注入(了解即可)

4.5.Lazy-init:延迟加载

lazy-init在scope属性为singleton时,才会有效。
true:表示在spring容器加载的时候不会初始化bean,而等到第一次使用时才会加载
false:表示spring容器初始化的时候就会加载

如果一个设置了立即加载的bean1引用了一个延迟加载的bean2,那么bean1在容器启动时被实例化,因为bean2的第一次时给了bean1,所以这种情况也符合延迟加载的bean在第一次调用时才被实例化的规则,bean2也会随着容器加载

4.6.Init-method/destroy-method:

init-method:  容器初始化后,对象被使用前就会执行,初始化一些必要的东西,避免用户访问的时候才去初始化
destroy: 容器关闭时会执行,常用来关闭资源
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--id:就是spring容器为当前对象,改的唯一标识-->
         <!--
                scope:指定bean是单例还是多例
                autowire:
                        byName:根据属性名称去ioc容器中取
                        byType:通过属性的类型查找JavaBean依赖的对象并为其注入。使用Seter方法为其注入。
                          如果根据接口类型注入,接口有多个实现类:
                          'cn.cdqf.dao.UserDao' available: expected single matching bean but found 2: userDao,userDao2
                lazy-init:懒加载
                        true:表示在spring容器加载的时候不会初始化bean,而等到第一次使用时才会加载
                        false:表示spring容器初始化的时候就会加载
                init-method:init:在对象中自定义的方法 名字可以自己取
                        容器初始化后,对象被使用前就会执行,初始化一些必要的东西,避免用户访问的时候才去初始化
                destroy:destroy:在对象中自定义的方法 名字可以自己取
                        容器关闭时会执行,常用来关闭资源

         -->
        <bean id="userService" class="cn.cdqf.service.impl.UserServiceImpl"
        scope="singleton"  lazy-init="false" init-method="init" destroy-method="destroy"></bean>

        <!--
                在把当前对象放入ioc容器中的时候 不仅根据名字放了 还根据类型放了
                而且还根据接口类型也放入了

        -->
       <!-- <bean id="userDao" class="cn.cdqf.dao.UserDaoImpl"></bean>-->
       <!-- <bean id="userDao2" class="cn.cdqf.dao.UserDaoImpl2"></bean>-->
</beans>

关于在spring 容器初始化 bean 和销毁前所做的操作定义方式有三种:1,3后面讲解

第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

第二种是:通过 在xml中定义init-method 和 destory-method方法

第三种是: 通过bean实现InitializingBean和 DisposableBean接口

5.BeanFactory和ApplicationContext的区别

源码阶段还会详细讲解

BeanFactory:

是Spring里面最原始的接口,提供了最简单的容器的功能,只提供了实例化对象和拿对象的功能;

获得bean的基本方法

ApplicationContext:

应用上下文,继承BeanFactory接口,它是Spring的一各更高级的容器(更多功能),提供了更多的有用的功能;

  1. 国际化(MessageSource)

  2. 访问资源,如URL和文件(ResourceLoader)

  3. 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层

  4. 消息发送、响应机制(ApplicationEventPublisher)

  5. AOP(拦截器)

两者装载bean的区别

BeanFactory:

BeanFactory在启动的时候不会去实例化Bean,从容器中拿Bean的时候才会去实例化;

ApplicationContext:

ApplicationContext在启动的时候就把所有的Bean全部实例化了。它还可以为Bean配置lazy-init=true来让Bean延迟实例化;

选择

延迟实例化的优点:(BeanFactory

应用启动的时候占用资源很少;对资源要求较高的应用,比较有优势;

不延迟实例化的优点: (ApplicationContext

\1. 所有的Bean在启动的时候都加载,系统运行的速度快;

\2. 在启动的时候所有的Bean都加载了,我们就能在系统启动的时候,尽早的发现系统中的配置问题

\3. 建议web应用,在启动的时候就把所有的Bean都加载了。(把费时的操作放到系统启动中完成)

6.spring的getBean方法

在这里插入图片描述

  //从容器中取出来对象
        UserService userService = (UserService)classPathXmlApplicationContext.getBean("userService");
        //根据接口类型
        UserService bean = classPathXmlApplicationContext.getBean(UserService.class);
        //根据自己类型
        UserServiceImpl bean1 = classPathXmlApplicationContext.getBean(UserServiceImpl.class);
       //根据名字(id,name) 指定类型
        UserService userService1 = classPathXmlApplicationContext.getBean("userService", UserService.class);

7.依赖注入(三种)

1.setter方法注入

1.1注入普通变量

在这里插入图片描述

1.2注入数组属性

在这里插入图片描述

1.3注入集合list与set

在这里插入图片描述

1.4propertie注入

在这里插入图片描述

1.5注入对象

在这里插入图片描述

2.构造注入

在这里插入图片描述

3.接口注入

了解一下

标签:容器,入门,spring,spring01,bean,org,ioc,log4j,注入
来源: https://blog.csdn.net/weixin_39160689/article/details/110927781