SpringBoot unit單元測試中無法自動注入RedisConnectionFactory

最終也沒有直接解決的一個問題,記錄下來

導包版本

pom中皆為自動版本

代碼

configuration
@Configuration
public class RedisConfig {
    @Bean
    public RedisConnectionFactory redisCF(){
        //如果什么參數(shù)都不設置,默認連接本地6379端口
        JedisConnectionFactory factory = new JedisConnectionFactory();
        return factory;
    }
}
test
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisTest {

    //  ↓始終無效
    @Autowired
    RedisConnectionFactory factory;
    @Test
    public void testRedis(){
        //得到一個連接
        RedisConnection conn = factory.getConnection();
        conn.set("hello".getBytes(), "world".getBytes());
        System.out.println(new String(conn.get("hello".getBytes())));
    }

}
  • 報錯信息:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.learn_1.config.RedisTest': Unsatisfied dependency expressed through field 'factory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  • 嘗試過的解決方法
  1. 忽略,idea有時可能抽風
  2. 將@Autowired改為@Resource

解決

pom文件中導入clients
  • pom如下
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
注意添加@SpringBootTest(classes = Application.class)注解
  1. 較高版本的spingboot中,test使用該注解需要添加括號內的值,這樣才能保證注入成功
注意目錄結構
目錄結構.png
  1. springboot只會掃描啟動類(Application)當前所在目錄以及其子目錄的文件,保證自己的@Configuration注解的類都在啟動類之下
  2. 注意test中的目錄結構,最好與上方一一對應

曲線救國

借助AnnotationConfigApplicationContext類來獲取spring應用上下文 通過getBean()方法獲取需要的bean

代碼如下:

public class RedisTest {

    @Test
    public void testRedis(){
        //得到一個連接
        // 以注解的形式把 bean 注入Spring 并獲取 Spring 的上下文環(huán)境
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        // 獲取自己配置的 bean 實例
        RedisConnectionFactory factory = ctx.getBean(RedisConnectionFactory.class);

        RedisConnection conn = factory.getConnection();
        conn.set("hello".getBytes(), "world".getBytes());
        System.out.println(new String(conn.get("hello".getBytes())));
    }

}
  • 通過該方式,只要容器中存在對應類型的bean,即可獲取到實例

總結

  1. 待補充
  2. 第一時間會考慮到導包問題/注解問題/設置問題/目錄問題等環(huán)境條件出錯,畢竟毫無內容
  3. 在解決之前需要先通過controller中接口以及config類中的斷點,確認RedisConnectionFactory 能夠正常使用
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容