七、SpringBoot的自动装配应用案例练习(结合Redis)
7.1、案例描述
7.2、案例实现
7.2.1、实现步骤
-
1、创建工程导入依赖
-
<?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>org.coolman</groupId> <artifactId>SpringBoot-Redis-Test</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <parent> <artifactId>spring-boot-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.5.0</version> </parent> <!--依赖管理--> <dependencies> <!--导入Spring的容器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--导入jedis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.3</version> </dependency> <!--SpringBoot测试启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> </project>
-
-
3、编写application.yml,编写redis的配置属性
-
myredis: host: 127.0.0.1 port: 6379
-
-
-
package com.coolman.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.Jedis; @EnableConfigurationProperties(RedisProperties.class) //加载 redis属性配置 @Configuration //声明是一个配置类 public class RedisConfiguration { @Autowired private RedisProperties redisProperties; @Bean public Jedis getJedis(){ return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
-
-
5、执行测试案例
-
package com.coolman; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBoottest; import redis.clients.jedis.Jedis; @Slf4j @SpringBoottest public class AppTest { @Autowired private Jedis jedis; @Test public void test01() { jedis.set("name", "coolman"); log.info("从redis读取到的数据:" + jedis.get("name")); } }
-
-
测试结果
7.3、总结
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。