spring框架

框架 spring

1 spring介绍 框架

框架:经过验证的,具有一定功能的,半成品软件

  • 经过验证

  • 具有一定功能

  • 半成品

框架作用:

  • 提高开发效率

  • 增强可重用性

  • 提供编写规范

  • 节约维护成本

  • 解耦底层实现原理

框架 xxx管理网站 框架 半成品项目

spring是一个全生态种 一站式常用框架

Spring 优点:

  • 方便解耦,简化开发
  • 方便集成各种框架
  • 方便程序测试
  • AOP 编程难过的支持
  • 声明式事务的支持
  • 降低 JavaEE API 的使用难度

​ Aop 编程的支持 程序对于事物的支持

spring 春天 spring 关键 是一个容器 装其他得框架其他得对象 使自己得项目变得强大

mybatis 它就会数据了 springmvc 它就会和浏览器链接 吃掉druid 就会数据库连接池了

spring容器+mybatis +springmvc + druid 项目就什么东西都会了 吸星大法

英雄联盟 虚空恐惧 大虫子 大招吃其他得英雄 吃一个人就壮大 自己就会变大

2 spring得 IOC 控制反转

ioc基本概述
  • IoC(Inversion Of Control)控制反转,Spring 反向控制应用程序所需要使用的外部资源
  • Spring 控制的资源全部放置在 Spring 容器中,该容器称为 IoC 容器(存放实例对象)
  • 官方网站:https://spring.io/ → Projects → spring-framework → LEARN → Reference Doc

  • 耦合(Coupling):代码编写过程中所使用技术的结合紧密度,用于衡量软件中各个模块之间的互联程度
  • 内聚(Cohesion):代码编写过程中单个模块内部各组成部分间的联系,用于衡量软件中各个功能模块内部的功能联系
  • 代码编写的目标:高内聚,低耦合。同一个模块内的各个元素之间要高度紧密,各个模块之间的相互依存度不紧密

spring注解 200多个 深入掌握

控制反转 将创建对象的权力交给spring 我们专注于业务的开发。 关注 service 层 测试比较方便 一个容器 方便我们使用

用spring创建对象 spring帮你管理对象

看一下spring怎样创建对象

模拟三层架构中表现层调用业务层功能

  • 表现层:UserApp 模拟 UserServlet(使用 main 方法模拟)

  • 业务层:UserService

1 写pom
父项目  pom
       <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.dunkai.springdemos</groupId>
      <artifactId>spring-project</artifactId>
      <version>1.0-SNAPSHOT</version>
      <properties>
          <maven.compiler.source>8</maven.compiler.source>
          <maven.compiler.target>8</maven.compiler.target>
          <spring-version>5.1.9.RELEASE</spring-version>
          <junit-version>4.10</junit-version>
      </properties>
     <dependencyManagement>
      <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring-version}</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</ar	tifactId>
          <version>${junit-version}</version>
          <scope>test</scope>
      </dependency>
      </dependencies>
     </dependencyManagement>
  </project>

 
 子项目 pom
 <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <parent>
          <artifactId>spring-project</artifactId>
          <groupId>com.dunkai.springdemos</groupId>
          <version>1.0-SNAPSHOT</version>
      </parent>
      <modelVersion>4.0.0</modelVersion>
      <artifactId>spring-day1</artifactId>
  
      <properties>
          <maven.compiler.source>8</maven.compiler.source>
          <maven.compiler.target>8</maven.compiler.target>
      </properties>
      <dependencies>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
          </dependency>
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <scope>test</scope>
          </dependency>
      </dependencies>
  
  </project>


  1. 编写业务层与表现层(模拟)接口与实现类 service.UserServiceservice.impl.UserServiceImpl

   java
   public interface UserService {
   	//业务方法  
   	void save();
   }
 

  java
   public class UserServiceImpl implements UserService {
       public void save() {
           System.out.println("user service running...");
       }
   }

    
2 编写spring的配置文件 application.xml 或 spring.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 注册的方式 
    Di  依赖注入  
    创建对象了  对象里面有属性    这些属性 是怎么赋值的  spring 可以赋值
    -->
        <bean id="userService" name="xiaoUser"   init-method="init"  scope="prototype"  destroy-method="destroy"   class="com.dunkai.service.impl.UserServiceImpl" />
    
<!--    userService 注入到userDao当中 set注入
        ref 引入  你引入的类一致   了解
        name 要和 类当中名字一致
 -->
  <bean id="userDao"  class="com.dunkai.dao.Impl.UserDaoImpl" >
        <property name="userService" ref="userService"></property>
    </bean>
 <!--  扫描的方式   -->
    <context:component-scan base-package="com.dunkai" />
    
    
    
      <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/my? characterEncoding=utf8&amp;serverTimezone=UTC"></property>
        <property name="username" value="root"/>
        <property name="password" value="liys@1234"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
        <property name="dataSource" ref="datasource"/>
    </bean>

    
 </bean>

	

生命周期

作用:定义 bean 对象在初始化或销毁时完成的工作

格式:

<bean init-method="init" destroy-method="destroy></bean>

取值:bean 对应的类中对应的具体方法名

实现接口的方式实现初始化,无需配置文件配置 init-method:

  • 实现 InitializingBean,定义初始化逻辑
  • 实现 DisposableBean,定义销毁逻辑

注意事项:

  • 当 scope=“singleton” 时,Spring 容器中有且仅有一个对象,init 方法在创建容器时仅执行一次
  • 当 scope=“prototype” 时,Spring 容器要创建同一类型的多个对象,init 方法在每个对象创建时均执行一次
  • 当 scope=“singleton” 时,关闭容器(.close())会导致 bean 实例的销毁,调用 destroy 方法一次
  • 当 scope=“prototype” 时,对象的销毁由垃圾回收机制 GC 控制,destroy 方法将不会被执行

bean 配置:

<!--init-method和destroy-method用于控制bean的生命周期-->
<bean id="userService3" scope="prototype" init-method="init" destroy-method="destroy" class="service.impl.UserServiceImpl"/>

业务层实现类:

public class UserServiceImpl implements UserService{
    public UserServiceImpl(){
        System.out.println(" constructor is running...");
    }

    public void init(){
        System.out.println("init....");
    }

    public void destroy(){
        System.out.println("destroy....");
    }

    public void save() {
        System.out.println("user service running...");
    }
}

测试类:

UserService userService = (UserService)ctx.getBean("userService3");
DI
依赖注入
  • IoC(Inversion Of Control)控制翻转,Spring 反向控制应用程序所需要使用的外部资源

  • DI(Dependency Injection)依赖注入,应用程序运行依赖的资源由 Spring 为其提供,资源进入应用程序的方式称为注入,简单说就是利用反射机制为类的属性赋值的操作

IoC 和 DI 的关系:IoC 与 DI 是同一件事站在不同角度看待问题


set 注入

标签: 标签, 的子标签

作用:使用 set 方法的形式为 bean 提供资源

格式:

<bean>
	<property />
    <property />
    .....
</bean>

基本属性:

  • name:对应 bean 中的属性名,要注入的变量名,要求该属性必须提供可访问的 set 方法(严格规范此名称是 set 方法对应名称,首字母必须小写)
  • value:设定非引用类型属性对应的值,不能与 ref 同时使用
  • ref:设定引用类型属性对应 bean 的 id ,不能与 value 同时使用
<property name="propertyName" value="propertyValue" ref="beanId"/>

代码实现:

  • DAO 层:要注入的资源

    public interface UserDao {
        public void save();
    }
    
    public class UserDaoImpl implements UserDao{
        public void save(){
            System.out.println("user dao running...");
        }
    }
    
  • Service 业务层

    public interface UserService {
        public void save();
    }
    
    public class UserServiceImpl implements UserService {
    	private UserDao userDao;
        private int num;
        
        //1.对需要进行注入的变量添加set方法
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
        
    	public void setNum(int num) {
            this.num = num;
        }
        
        public void save() {
            System.out.println("user service running..." + num);
            userDao.save();
            bookDao.save();
        }
    }
    
  • 配置 applicationContext.xml

    <!--2.将要注入的资源声明为bean-->
    <bean id="userDao" class="dao.impl.UserDaoImpl"/>
    
    <bean id="userService" class="service.impl.UserServiceImpl">
    	<!--3.将要注入的引用类型的变量通过property属性进行注入,-->
        <property name="userDao" ref="userDao"/>
        <property name="num" value="666"/>
    </bean>
    
  • 测试类

    public class UserApp {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = (UserService) ctx.getBean("userService");
            userService.save();
        }
    }
    
3 编写spring的配置文件 编写类 通过spring注册为对象

package com.dunkai.service.impl;

import com.dunkai.dao.UserDao;
import com.dunkai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
//  吸星大法
// ioc方式 将UserServiceImpl 创建  放进spring容器里‘
@Service("userService")     // 代表将 UserServiceImpl 注入到spring当中
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserDao userDao;

    // 再UserServiceImpl 出生的时候你要做什么事情
/*
 // spring对象的生命周期
    public void  init(){
        System.out.println("UserServiceImpl出生了");
    }

    public void  destroy(){
        System.out.println("我是在对象销毁时执行的方法");
    }

*/


    @Override
    public int deleteUserById(String id) {

        int i = userDao.deleteUserbyId();
        if (i<=0){
            System.out.println("删除失败");
        }else {
            System.out.println("删除成功");
        }

        return 0;
    }
    @Override
    public List<Object> queryUsers() {
        return null;
    }
}

测试类 -------------------------------------------------------------------------------
    
    
     @Test
    public void test() {
        
        // 先加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");

        Environment environment = context.getEnvironment();

        // 获取与此组件关联的环境
        System.out.println(environment.toString());
}
    
    
    
    /*

        // 它是获取容器当中所有的对象      userService啊
        String[] beanDefinitionNames = context.getBeanDefinitionNames();

        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
        上万个对象
*/
    
    
    /
//        // 从容器当中获取对象    userService   这个对象是spring帮我们创建的
//        UserService userService = (UserService)context.getBean("xiaoUser");
//        UserService userServic1 = (UserService)context.getBean("xiaoUser");
//
//        System.out.println(userService==userServic1);  // true  false*/


    
     /*   @Test
    public void test1() {

        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        UserDao userDao = (UserDao)context.getBean("userDao");
        userDao.deleteUserbyId();


    }*/
    
     @Test
    public void test1() {

        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        UserService userService = (UserService)context.getBean("userService");
        userService.deleteUserById("1111");


    }


获取Bean

ApplicationContext 子类相关API:

方法说明
String[] getBeanDefinitionNames()获取 Spring 容器中定义的所有 JavaBean 的名称
BeanDefinition getBeanDefinition(String beanName)返回给定 bean 名称的 BeanDefinition
String[] getBeanNamesForType(Class<?> type)获取 Spring 容器中指定类型的所有 JavaBean 的名称
Environment getEnvironment()获取与此组件关联的环境
  • 21
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值