程序员书籍笔记 程序员书籍笔记
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • Vue

  • Nuxt

  • Echarts

  • Node

  • git

  • express

  • 微信小程序

  • Spring

    • Spring基础01
    • Spring基础02
      • Spring资源整合
      • 快速开始
        • 使用 properties
        • 配置 properties
      • Spring容器
        • 创建容器
        • 获取Bean对象
        • Bean和DI相关属性
      • 注解开发
        • 快速开始
        • 配置类设置
        • 注解Bean生命周期
        • 注解依赖注入
        • 第三方包设置
        • 图片注解总结
      • 整合第三方
        • Mybatis
        • Junit
    • Spring基础03
    • SpringMVC基础01
    • SpringMVC基础02
    • Mybatis基础01
    • MybatisPlus基础01
    • SpringBoot快速开始
  • 后端知识

  • Markdown

  • project

  • 自用文档查询

  • 框架和软件
  • Spring
yuadh
2022-10-09
目录

Spring基础02

# Spring资源整合

# 快速开始

示例:使用数据库连接库

  1. 添加依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.16</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
  1. 配置Bean对象
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>
1
2
3
4
5
6
  1. 测试类使用
public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource);
    }
}
1
2
3
4
5
6
7

# 使用 properties

将配置文件解耦,把数据库信息放置到 properties 文件中

  1. 编写 jdbc.properties 文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root
1
2
3
4
  1. 设置 Spring 配置文件的文件头
<?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">
    <context:property-placeholder location="jdbc.properties"/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
  1. 使用配置文件的内容
<bean class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
1
2
3
4
5
6

# 配置 properties

# 不加系统属性

context:property-placeholder在使用中可能会有用到系统属性的问题

解决方法

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

设置不适用系统名

# 加载多个文件

使用 , 分割

<context:property-placeholder location="jdbc.properties,msg.properties"/>

# 加载所有文件

<context:property-placeholder location="*.properties"/>

# 加载标准文件

<context:property-placeholder location="classpath:*.properties"/>

# Spring容器

# 创建容器

  • 方式一:类路径加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
1
  • 方式二:文件路径加载配置文件
ApplicationContext ctx = new FileSystemXmlApplicationContext("D:\\applicationContext.xml");
1
  • 加载多个配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean1.xml", "bean2.xml");
1

# 获取Bean对象

  • 方式一:使用bean名称获取

弊端:需要自己强制类型转换

BookDao bookDao = (BookDao) ctx.getBean("bookDao");
1
  • 方式二:使用bean名称获取并指定类型

弊端:推荐使用

BookDao bookDao = ctx.getBean("bookDao", BookDao.class);
1
  • 方式三:使用bean类型获取

弊端:如果IOC容器中同类型的Bean对象有多个,此处获取会报错

BookDao bookDao = ctx.getBean(BookDao.class);
1

# image-20210730102842030.png

BeanFactory 顶层接口

Resource resources = new ClassPathResource("applicationContext.xml");
BeanFactory bf = new XmlBeanFactory(resources);
BookDao bookDao = bf.getBean("bookDao", BookDao.class);
bookDao.save();
1
2
3
4

BeanFactory创建完毕后,所有的Bean均为延迟加载,也就是说我们调用getBean()方法获取Bean对象时才创建Bean对象并返回给我们

# Bean和DI相关属性

Bean

1665365183791.png

DI

1665365219607.png

# 注解开发

Component Bean注解,Spring 提供了三个衍生的注解

  • @Controller 表现层 bean 定义
  • @Service 业务层 bean 定义
  • @Repository 数据层 bean 定义

# 快速开始

  1. 开启 Spring 注解包的扫描
<?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">
    <context:component-scan base-package="com.yuadh"/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
  1. 在对象类上定义 注解
@Component("bookDao")
public class BookDaoImpl implements BookDao , InitializingBean, DisposableBean {

    @Override
    public void save() {
        System.out.println("book dao save...");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("destory auto...");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("init auto");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    public BookServiceImpl(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    @Override
    public void save() {
        System.out.println("book server loading...");
    }
    public void setBookDao(BookDaoImpl bookDao) {
        this.bookDao = bookDao;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  1. 测试类,注意获取 bean 对象的方式有多种
public class AppForAnnotation {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        System.out.println(bookDao);
        //按类型获取bean
        BookService bookService = ctx.getBean(BookService.class);
        System.out.println(bookService);
    }
}
1
2
3
4
5
6
7
8
9
10

# 配置类设置

纯注解开发模式,使用 Java 类替代 xml 配置文件

  • Configuration 设定当前类为配置类
  • ComponentScan 用于设定扫描路径
//加载配置类初始化容器
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
1
2

示例

配置类

@Configuration
@ComponentScan({"com.yuadh"})
public class SpringConfig {

}
1
2
3
4
5

测试类

public class SpringUse03 {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        bookDao.save();
        BookService bookService = ctx.getBean(BookService.class);
        bookService.save();
    }
}
1
2
3
4
5
6
7
8
9

# 注解Bean生命周期

作用范围

@Scope

@Repository
@Scope("singleton")
public class BookDaoImpl implements BookDao {
}
1
2
3
4

生命周期

  • @PostConstruct
  • @PreDestory
@Repository
@Scope("singleton")
public class BookDaoImpl implements BookDao {
    public BookDaoImpl() {
        System.out.println("book dao constructor ...");
    }
    @PostConstruct
    public void init(){
        System.out.println("book init ...");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("book destory ...");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

这两个注解在JDK9 中被废除了 ,可以通过第三方包导入

<dependency>
  <groupId>javax.annotation</groupId>
  <artifactId>javax.annotation-api</artifactId>
  <version>1.3.2</version>
</dependency>
1
2
3
4
5

# 注解依赖注入

@Autowired,自动装配

@Service
public class BookServiceImpl implements BookService {
    //@Autowired:注入引用类型,自动装配模式,默认按类型装配
    @Autowired
    private BookDao bookDao;

    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
    }
}
1
2
3
4
5
6
7
8
9
10
11

在注解包扫描下,会有自动装配 Bean 对象

# Qualifier

指定要装配的 Bean 名称,可以解决容易中同类型 Bean 有多个装配问题

@Service
public class BookServiceImpl implements BookService {
    //@Autowired:注入引用类型,自动装配模式,默认按类型装配
    @Autowired
    //@Qualifier:自动装配bean时按bean名称装配
    @Qualifier("bookDao")
    private BookDao bookDao;

    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

@Qualifier 无法单独使用,必须搭配 @Autowired

# Value 简单类型

简单类型的注入

@Repository("bookDao")
public class BookDaoImpl implements BookDao {
    //@Value:注入简单类型(无需提供set方法)
    @Value("${name}")
    private String name;

    public void save() {
        System.out.println("book dao save ..." + name);
    }
}
1
2
3
4
5
6
7
8
9
10

${name} 为配置文件中的键值对

@Configuration
@ComponentScan("com.itheima")
//@PropertySource加载properties配置文件
@PropertySource({"classpath:jdbc.properties"}) //{}可以省略不写
public class SpringConfig {
}
1
2
3
4
5
6

# 第三方包设置

加入容器

  1. 定义加载类
public class JdbcConfig {
    //@Bean:表示当前方法的返回值是一个bean对象,添加到IOC容器中
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring_db");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
  1. 加入到配置类中

@Import 注解导入方式

@Configuration
@ComponentScan("com.itheima")
//@Import:导入配置信息
@Import({JdbcConfig.class})
public class SpringConfig {
}
1
2
3
4
5
6

或者包含到 @ComponentScan 扫描包中

@Configuration
@ComponentScan({"com.yuadh"})  //只要com.itheima.config包扫到了就行,三个包可以合并写成com.itheima
public class SpringConfig {
}
1
2
3
4

为第三方Bean注入依赖

  • 简单类型注入
public class JdbcConfig {
    //1.定义一个方法获得要管理的对象
    @Value("com.mysql.jdbc.Driver")
    private String driver;
    @Value("jdbc:mysql://localhost:3306/spring_db")
    private String url;
    @Value("root")
    private String userName;
    @Value("root")
    private String password;
    //2.@Bean:表示当前方法的返回值是一个bean对象,添加到IOC容器中
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  • 引用类型注入
//Spring会自动从IOC容器中找到BookDao对象赋值给参数bookDao变量,如果没有就会报错。
@Bean 
public DataSource dataSource(BookDao bookDao){
    System.out.println(bookDao);
    DruidDataSource ds = new DruidDataSource();
    ds.setDriverClassName(driver);
    ds.setUrl(url);
    ds.setUsername(userName);
    ds.setPassword(password);
    return ds;
}
1
2
3
4
5
6
7
8
9
10
11

# 图片注解总结

1665369215975.png

# 整合第三方

# Mybatis

对 Mybatis 进行封装,需要获取到 SqlSessionFactoryBean 封装环境信息,需要获取到 MapperScannerConfigurer 加载Dao接口

这些对象需要存储到 Spring 容器中

准备数据对象

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

准备数据层接口

public interface AccountDao {

    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tbl_account")
    List<Account> findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

准备服务层

public interface AccountService {
    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);
}
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }
    @Override
    public void update(Account account){
        accountDao.update(account);
    }
    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }
    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }
    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 导入相关依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11

# 创建数据库Bean

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 配置Mybatis相关Bean

public class MybatisConfig {
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.yuadh.POJO");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.yuadh.dao");
        return msc;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • Dao 包里只能包含相关 Mapper

# 配置类设置

@Configuration
@ComponentScan({"com.yuadh"})
@PropertySource({"classpath:jdbc.properties"})
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {

}
1
2
3
4
5
6
7

# 测试类测试

public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService accountService = ctx.getBean(AccountService.class);

        Account ac = accountService.findById(1);
        System.out.println(ac);
    }
}
1
2
3
4
5
6
7
8
9
10

# Junit

测试单元

# 导入依赖包

<!--junit-->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.1.9.RELEASE</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12

# 使用

//【第二步】使用Spring整合Junit专用的类加载器
@RunWith(SpringJUnit4ClassRunner.class)
//【第三步】加载配置文件或者配置类
@ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})//加载配置文件
public class AccountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private AccountService accountService;

    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));
    }

    @Test
    public void testFindAll(){
        System.out.println(accountService.findAll());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
编辑 (opens new window)
上次更新: 2023/02/07, 14:51:48
Spring基础01
Spring基础03

← Spring基础01 Spring基础03→

Theme by Vdoing | Copyright © 2021-2023 yuadh
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×