Spring第1天(介绍,配置核心文件,创建及使用对象)

Spring

spring框架:

  1. 是一个开源的免费的框架(创建对象的容器)
  2. 是一个轻量级的控制反转(IOC)和面向切面(AOP)编程的框架

image
image
image

mybatis优化dao层
spring用来优化service层(service实现类层-->new XXXDaoImpl对象)

IOC

IOC:控制反转又叫依赖注入
1.控制反转:将创建对象的权力交给spring容器来实现(本来创建对象使需要在相关的代码中使用new来实现,而有了spring之后只需在配置文件中配置,spring容器自动创建对象)
2. 依赖注入:依赖容器创建对象,并且将值注入到相关的变量中

核心配置文件

JavaBean
class:要创建对象的类(全路径:包含包名)
id:对应的对象名字
注意:如果没有特别指定,则bean标签相当于在调用无参构造
官网中的位置:
image

<?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="..." class="..."> 
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>
  1. 创建对象(在配置文件中):
 <bean id="helloSpring" class="test.HelloSpring">
        <!-- collaborators and configuration for this bean go here -->
		<property name="对象名" value="对象值"></property>
    </bean>
  1. 如果给该对象的属性值需要传进来一个对象,需要使用ref属性(注意,传进来的对象需要在上面创建好)
``` ``` 2. 使用对象: ``` //实例化spring核心对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); HelloSpring hs= (HelloSpring)ac.getBean("helloSpring"); ```
posted @ 2022-12-02 12:06  不再犹豫27  阅读(49)  评论(0)    收藏  举报