• Spring学习+Spring整合durid+Spring整合Mybatis


    目录

    1 集合注入

    2 IOC/DI配置管理第三方bean

    Spring整合durid

    3 IOC容器 

    1,2,3总结 

    4 IOC/DI注解开发 

    半注解开发

     纯注解开发模式

    Bean的作用范围体验生命周期

    自动装配

    IOC/DI注解开发管理第三方bean

    Spring整合Mybatis

    1 准备SQL,建立数据库

    2 依赖导入

    3 创建以下大致目录

    4 主配置类中读properties并引入数据源配置类

    5 创建Mybatis配置类并配置SqlSessionFactory

    6 主配置类中引入Mybatis配置类

    7 编写Dao层与Service和测试文件

    最终结构

    测试文件

    源码


    1 集合注入

            总结起来就那几点

    第一点使用咱的property标签 给他一个name注意这个name和咱在接口实现类中的集合类型数据的name是相对应的。

    第2点在里面写入集合标签比如咱常见的array list、map set还有我们的properties List set array在标签内部使用value引入各个值, 而map使用entry里面有两个属性一个T一个value分别对应键和值,最后就是咱最常见的properties类型数据里面用专有标签prop

    2 IOC/DI配置管理第三方bean

    Spring整合durid

    1 maven依赖

    1. <dependency>
    2. <groupId>org.springframeworkgroupId>
    3. <artifactId>spring-contextartifactId>
    4. <version>5.2.10.RELEASEversion>
    5. dependency>
    6. <dependency>
    7. <groupId>junitgroupId>
    8. <artifactId>junitartifactId>
    9. <version>4.12version>
    10. <scope>testscope>
    11. dependency>
    12. <dependency>
    13. <groupId>com.alibabagroupId>
    14. <artifactId>druidartifactId>
    15. <version>1.2.14version>
    16. dependency>
    17. <dependency>
    18. <groupId>mysqlgroupId>
    19. <artifactId>mysql-connector-javaartifactId>
    20. <version>8.0.31version>
    21. dependency>

    2 配置第三方配置文件

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://127.0.0.1:3306/task1
    3. jdbc.username=root
    4. jdbc.password=xxxz

    3 配置SpringXml文件

    四个要点

    第1个要点引入上下文及xmlns:context,

    第2个要点引入xsi

    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">

    第3个要点使用context标签将外部配置文件引入,具体就是location等于resources资源目录下的某个配置文件。

    第4个就是填充一些变量喽,新建一个bean里面去将每个变量用property标签表示出来,这里填充变量用的是到刀了符大括号。

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="
    6. http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring-context.xsd">
    10. <context:property-placeholder location="db.properties"/>
    11. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    12. <property name="driverClassName" value="${jdbc.driver}"/>
    13. <property name="url" value="${jdbc.url}"/>
    14. <property name="username" value="${jdbc.username}"/>
    15. <property name="password" value="${jdbc.password}"/>
    16. bean>
    17. beans>

    编写测试类

    1. package org.example.Dao;
    2. public class BookDaoImpl implements BookDao{
    3. private String name;
    4. public void setName(String name) {
    5. this.name = name;
    6. }
    7. public void save() {
    8. System.out.println("book dao save ..." + name);
    9. }
    10. }
    11. package org.example.Dao;
    12. public interface BookDao {public void save();
    13. }
    14. @Test
    15. public void alibbTest()
    16. {
    17. ApplicationContext ctx = new
    18. ClassPathXmlApplicationContext("applicationContext.xml");
    19. //getBean()需要注入项的id
    20. DataSource dataSource = (DataSource) ctx.getBean("dataSource");
    21. System.out.println(dataSource);
    22. }

    最佳实践

    system-properties-mode:设置为NEVER,表示不加载系统属性

    另外配置文件中的项要加上前缀

    <context:property-placeholder location="" system-properties-mode="NEVER"/>

    3 IOC容器 

    1 容器创建

    1. //=类路径下的XML配置文件
    2. ApplicationContext ctx = new
    3. ClassPathXmlApplicationContext("applicationContext.xml");
    4. //文件系统下的XML配置文件
    5. ApplicationContext ctx2=new FileSystemXmlApplicationContext("F:\\JAVA EE Preject\\SpringLearn\\Springday2\\src\\main\\resources\\applicationContext.xml");

    2 Bean的三种获取方式

    1. //getBean()需要注入项的id
    2. //1 常用方法
    3. DataSource dataSource = (DataSource) ctx.getBean("dataSource");
    4. //2 确保就类似我们之前所学习依赖注入中的按类型注入。必须要确保IOC容器中该类型对应的bean对象只有一个
    5. DataSource dataSource1 = ctx.getBean(DataSource.class);
    6. //3 推荐,第一个参数还是id,第二个是类型
    7. DataSource dataSource2 = ctx.getBean("dataSource", DataSource.class);

    3 IOC容器创建使用BeanFactory与ApplicationContext的区别

     

    1,2,3总结 

     

    4 IOC/DI注解开发 

    半注解开发

    注解开发定义bean

    1 使用@Componnet("id名")注释在接口的实现类上

    2 配置Spring.xml使其能够扫描到注解 

    3 编写测试类 

     

    关于其他注解

     纯注解开发模式

    1 删除掉原来的Springxml配置文件

    2 创建配置类

     3 在来这个类中添加配置注解,同时添加包注释,需要扫描的类也要注解

    1. package org.example.Config;
    2. import org.springframework.context.annotation.ComponentScan;
    3. import org.springframework.context.annotation.Configuration;
    4. @Configuration
    5. @ComponentScan("org.example.Dao")
    6. public class SpringConfig {
    7. }

    4 修改测试类

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

    5 运行

     6 总结

    Bean的作用范围体验生命周期

     

    Bean的初始化与销毁

    @PostConstruct //在构造方法之后执行,初始化
    public void init() {
        System.out.println("init ...");
    }
    @PreDestroy//预销毁的意思 需要注意的是 destroy 只有在容器关闭的时候,才会执行
    public void destroy() {
        System.out.println("destroy ...");
    }

     @PostConstruct和@PreDestroy注解如果找不到,需要导入下面的jar包== 找不到的原因是,从JDK9以后jdk中的javax.annotation包被移除了,这两个注解刚好就在这个包中

    
    javax.annotation
    javax.annotation-api
    1.3.2
    

    对应关系

    自动装配

    在需要的类的属性上加上

    @AutoWired即可 

             但是如果出现接口的实现类有多个的时候,如果不去指定名称就会报错

    ,如果指定的名称不合法也会报错

    例题

    图1

     情况1

     可以正常注入,不会报错

    情况2

     会报错,因为指定的名称里面没有对应的属性名()就是实现类里面的属性名称里(看 图1)

    最佳实践

    在Service的实现类上使用@qualifierm来指定具体是那个DaoImpl,注意它离不开@Autowire

     基本类型注入

    @Value 一般会被用在从properties配置文件中读取内容进行使用

     注解读取properties配置文件

    1 准备配置文件

     2 在配置类中添加注释

    3 使用 

    IOC/DI注解开发管理第三方bean

    Spring整合Mybatis

    1 准备SQL,建立数据库

    create database spring_db character set utf8; use spring_db; create table tbl_account( id int primary key auto_increment, name varchar(35), money double );


    INSERT INTO `tbl_account` VALUES (1, '张三', 1000);
    INSERT INTO `tbl_account` VALUES (2, '王五', 1090);

    2 依赖导入

    注意顺序不能颠倒

    1. <dependency>
    2. <groupId>org.springframeworkgroupId>
    3. <artifactId>spring-contextartifactId>
    4. <version>5.2.10.RELEASEversion>
    5. dependency>
    6. <dependency>
    7. <groupId>com.alibabagroupId>
    8. <artifactId>druidartifactId>
    9. <version>1.1.16version>
    10. dependency>
    11. <dependency>
    12. <groupId>mysqlgroupId>
    13. <artifactId>mysql-connector-javaartifactId>
    14. <version>5.1.47version>
    15. dependency>
    16. <dependency>
    17. <groupId>org.springframeworkgroupId>
    18. <artifactId>spring-jdbcartifactId>
    19. <version>5.2.10.RELEASEversion>
    20. dependency>
    21. <dependency>
    22. <groupId>org.mybatisgroupId>
    23. <artifactId>mybatis-springartifactId>
    24. <version>1.3.0version>
    25. dependency>
    26. <dependency>
    27. <groupId>org.mybatisgroupId>
    28. <artifactId>mybatisartifactId>
    29. <version>3.5.6version>
    30. dependency>

    3 创建以下大致目录

    具体内容如下

    1 entity 实体类 Account.java

    1. public class Account implements Serializable {
    2. private Integer id;
    3. private String name;
    4. private Double money;
    5. //setter...getter...toString...方法略
    6. }

    2 resources 添加JDBC/mysql配置文件 db.properties

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://127.0.0.1:3306/task1?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=x

    useSSL:关闭MySQL的SSL连接 

    3 Springconfig 添加Spring配置类 SpringConfig.java

    1. package com.mybatis.Springconfig;
    2. import org.springframework.context.annotation.ComponentScan;
    3. import org.springframework.context.annotation.Configuration;
    4. //配置类注解
    5. @Configuration
    6. //包扫描,主要扫描的是项目中的AccountServiceImpl类
    7. @ComponentScan("com.mybatis.service")
    8. public class SpringConfig {
    9. }

    4 dataSourceCofig 创建数据源的配置类  JdbcConfig.java

    1. package com.mybatis.dataSourceConfig;
    2. import com.alibaba.druid.pool.DruidDataSource;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.context.annotation.Bean;
    5. import javax.sql.DataSource;
    6. public class JdbcConfig {
    7. @Value("${jdbc.driver}")
    8. private String driver;
    9. @Value("${jdbc.url}")
    10. private String url;
    11. @Value("${jdbc.username}")
    12. private String userName;
    13. @Value("${jdbc.password}")
    14. private String password;
    15. @Bean
    16. public DataSource dataSource(){
    17. DruidDataSource ds = new DruidDataSource();
    18. ds.setDriverClassName(driver);
    19. ds.setUrl(url);
    20. ds.setUsername(userName);
    21. ds.setPassword(password);
    22. return ds;
    23. }
    24. }

    4 主配置类中读properties并引入数据源配置类

    1. package com.mybatis.Springconfig;
    2. import com.mybatis.dataSourceConfig.JdbcConfig;
    3. import org.springframework.context.annotation.ComponentScan;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.context.annotation.Import;
    6. import org.springframework.context.annotation.PropertySource;
    7. //配置类注解
    8. @Configuration
    9. //包扫描,主要扫描的是项目中的AccountServiceImpl类
    10. @ComponentScan("com.mybatis.service")
    11. //加载配置文件内容
    12. @PropertySource("classpath:db.properties")
    13. //注入Jdbc
    14. @Import(JdbcConfig.class)
    15. public class SpringConfig {
    16. }

    5 创建Mybatis配置类并配置SqlSessionFactory

    1. package com.mybatis.mybatisConfig;
    2. import org.mybatis.spring.SqlSessionFactoryBean;
    3. import org.mybatis.spring.mapper.MapperScannerConfigurer;
    4. import org.springframework.context.annotation.Bean;
    5. import javax.sql.DataSource;
    6. public class MybatisConfig {
    7. //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    8. @Bean
    9. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
    10. SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
    11. //设置模型类的别名扫描
    12. ssfb.setTypeAliasesPackage("com.mybatis.domain");
    13. //设置数据源
    14. ssfb.setDataSource(dataSource);
    15. return ssfb;
    16. }
    17. //定义bean,返回MapperScannerConfigurer对象
    18. @Bean
    19. public MapperScannerConfigurer mapperScannerConfigurer(){
    20. MapperScannerConfigurer msc = new MapperScannerConfigurer();
    21. msc.setBasePackage("com.mybatis.dao");
    22. return msc;
    23. }
    24. }

    6 主配置类中引入Mybatis配置类

    1. package com.mybatis.Springconfig;
    2. import com.mybatis.dataSourceConfig.JdbcConfig;
    3. import com.mybatis.mybatisConfig.MybatisConfig;
    4. import org.springframework.context.annotation.ComponentScan;
    5. import org.springframework.context.annotation.Configuration;
    6. import org.springframework.context.annotation.Import;
    7. import org.springframework.context.annotation.PropertySource;
    8. //配置类注解
    9. @Configuration
    10. //包扫描,主要扫描的是项目中的AccountServiceImpl类
    11. @ComponentScan("com.mybatis.service")
    12. //加载配置文件内容
    13. @PropertySource("classpath:db.properties")
    14. //注入Jdbc
    15. @Import({JdbcConfig.class, MybatisConfig.class})
    16. public class SpringConfig {
    17. }

    7 编写Dao层与Service和测试文件

    dao

    1. package com.mybatis.dao;
    2. import com.mybatis.entity.Account;
    3. import org.apache.ibatis.annotations.Delete;
    4. import org.apache.ibatis.annotations.Insert;
    5. import org.apache.ibatis.annotations.Select;
    6. import org.apache.ibatis.annotations.Update;
    7. import java.util.List;
    8. public interface AccountDao {
    9. @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    10. void save(Account account);
    11. @Delete("delete from tbl_account where id = #{id} ")
    12. void delete(Integer id);
    13. @Update("update tbl_account set name = #{name} , money = #{money} where id =#{id} ")
    14. void update(Account account);
    15. @Select("select * from tbl_account")
    16. List findAll();
    17. @Select("select * from tbl_account where id = #{id} ")
    18. Account findById(Integer id);
    19. }

     service

    1. package com.mybatis.service;
    2. import com.mybatis.entity.Account;
    3. import java.util.List;
    4. public interface AccountService {
    5. void save(Account account);
    6. void delete(Integer id);
    7. void update(Account account);
    8. List findAll();
    9. Account findById(Integer id);
    10. }
    1. package com.mybatis.service;
    2. import com.mybatis.dao.AccountDao;
    3. import com.mybatis.entity.Account;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import java.util.List;
    7. @Service
    8. public class AccountServiceImpl implements AccountService {
    9. @Autowired
    10. private AccountDao accountDao;
    11. public void save(Account account) {
    12. accountDao.save(account);
    13. }
    14. public void update(Account account){
    15. accountDao.update(account);
    16. }
    17. public void delete(Integer id) {
    18. accountDao.delete(id);
    19. }
    20. public Account findById(Integer id) {
    21. return accountDao.findById(id);
    22. }
    23. public List findAll() {
    24. return accountDao.findAll();
    25. }
    26. }

    最终结构

    测试文件

    1. import com.mybatis.Springconfig.SpringConfig;
    2. import com.mybatis.entity.Account;
    3. import com.mybatis.service.AccountService;
    4. import org.junit.Test;
    5. import org.springframework.context.ApplicationContext;
    6. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    7. public class SpringMybatisTest {
    8. @Test
    9. public void MybatisTest()
    10. {
    11. ApplicationContext ctx = new
    12. AnnotationConfigApplicationContext(SpringConfig.class);
    13. AccountService accountService = ctx.getBean(AccountService.class);
    14. Account ac = accountService.findById(1);
    15. System.out.println(ac);
    16. }
    17. }

    源码

    链接:https://pan.baidu.com/s/1HTia58FluOrOzazGfz8HFw?pwd=gtt1 
    提取码:gtt1

  • 相关阅读:
    JavaSE——学习总结
    mysql死锁查看
    Pycharm的python Interpreter打不开
    K8S集群部署问题及处理记录
    Hutool 工具类之日期时间工具-DateUtil mysql日期字段
    Python 物联网之用于基于 TinyFlux的物联网和分析应用程序的微型时间序列数据库
    6.1810: Operating System Engineering Lab: Xv6 and Unix utilities By:Haostart
    《深入浅出OCR》第三章:OCR文字检测
    将json数据转换为Python字典
    实验九—基本统计分析(二)
  • 原文地址:https://blog.csdn.net/qq_53679247/article/details/127808841