Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.test.service.FurnService’ available.
本质就是IOC控制反转。
你自动注入的JavaBean是要用这个JavaBean去真正实现这个添加或者删除等某个方法。
因此,添加注解的需要是真正实现、调用方法的那个类。所以肯定不能是接口。
为什么?
接口是不能实例化的。你需要的是在BeanFactory中一个可以实现这个方法的JavaBean。
而你想在BeanFactory中实例化一个接口?
不现实吧
package com.test.servicec;
import furn.bean.Furn;
import furn.service.FurnService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.math.BigDecimal;
/**
* @Author: GQLiu
* @DATE: 2024/3/25 20:49
*/
public class FurnServiceTest {
private ApplicationContext ioc;
private FurnService furnService;
@Before
public void init() {
ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
furnService = ioc.getBean(FurnService.class);
System.out.println("furnService=" + furnService.getClass()); // furnService=class com.sun.proxy.$Proxy23
}
@Test
public void saveTest() {
// 测试FurnService中的save()方法
Furn furn = new Furn(null, "小MacBook", "Apple", new BigDecimal(90), 666, 7, "assets/images/product-image/4.jpg");
// 这里的furnService是一个代理对象,通过控制反转IOC注入到BeanFactory中,然后调用真正执行这个 save方法
furnService.save(furn);
System.out.println("添加成功");
}
}
参考:
https://blog.csdn.net/qq_35923749/article/details/77159213
https://blog.51cto.com/u_15127644/2756683