使用getbean 报No qualifying bean of type 'xxx' available的一种解决办法

首先有一个接口

public interface EmployeeService {

    Employee getEmployee(Provider provider) throws SQLException;

}

然后有两个实现类

@Service("EmployeeAService")
public class EmployeeAServiceImpl implements EmployeeService {
   xxx
}
@Service("EmployeeBService")
public class EmployeeBServiceImpl implements EmployeeService {
   xxx
}

某类

@Service
public class EmployeeServiceFactory implements ApplicationContextAware {

    private ApplicationContext factory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.factory = applicationContext;
    }
    //或者不用implements ApplicationContextAware直接使用
    //@Autowired
    //private ApplicationContext applicationContext;注入


    public Employee getEmployee(Provider provider, Integer xx) throws SQLException {
        switch (xx) {
            case 1:
                return this.factory.getBean(EmployeeAServiceImpl.class).getEmployee(provider);
            default:
                return this.factory.getBean(EmployeeBServiceImpl.class).getEmployee(provider);
        }
    }
}

若这样直接使用会报标题的错误

这是因为这里会使用jdk动态代理。原因是:如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP

因为这样生成的类,名字是类似$Proxy75,因而会报不可用。

解决办法,可以加proxy-target-class="true"

强制使用CGLIB代理方式 如在applicationContex.xml文件中如下

若是注解方式的,可以@EnableAspectJAutoProxy(proxyTargetClass= true)

另一种方法是,

this.factory.getBean("EmployeeAService",EmployeeService.class).getEmployee(provider);

或者

EmployeeService  aService = (EmployeeService)this.factory.getBean("EmployeeAService")
aService.getEmployee(provider) 

 

你可能感兴趣的:(Spring)