Java 如何在服务层内调用服务
在我的服务层Java 如何在服务层内调用服务,java,spring,spring-mvc,aop,Java,Spring,Spring Mvc,Aop,在我的服务层 public class MyServiceLayerImpl{ public void method1(){ MyServicelayer.method(); //is this correct? } public void method2(){ } @Autowired MyServiceInterface MyServiceLayer; } 如果我在服务层中有一个方法,它需要调用服务层中的另一个服务
public class MyServiceLayerImpl{
public void method1(){
MyServicelayer.method(); //is this correct?
}
public void method2(){
}
@Autowired
MyServiceInterface MyServiceLayer;
}
如果我在服务层中有一个方法,它需要调用服务层中的另一个服务。我无法使用此.\u方法,因为我正在使用AOP进行缓存。为了让缓存工作,我必须使用@Autowired
来获取服务。因此,上面的样式可以吗
我得到下面的错误
原因:org.springframework.beans.factory.BeanCreationException:创建名为'com.company.iss.services.MyServiceLayerImpl#85aedd'的bean时出错:字段自动连接失败;嵌套异常为org.springframework.beans.factory.BeanCreationException:无法自动关联字段:com.company.iss.services.MyServicelayer com.company.iss.services.MyServiceLayerImpl.MyServicelayer;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:未定义类型为[com.company.iss.services.MyServiceLayer]的唯一bean:类型为[interface com.company.iss.services.MyServiceLayer]的未满足依赖项:至少需要1个匹配bean
除了有一个大写变量和没有冒号-这很好 当然,您需要将类定义为bean。通过在其上使用
@Service
(或另一个原型)注释,或在applicationContext.xml
中使用
(用于spring 2中引入的基于注释的配置)
另一件事:您的成员变量应该是小写,而不是大写。很难从奇怪的格式和命名中分辨出来,但是如果您想从一个服务调用另一个服务:
public interface MasterService {
void someMethod();
}
public class MasterServiceImpl implements MasterService {
private OtherService otherService;
public void someMethod() {
this.otherService.someCallOnOtherService();
}
@Autowired
public void setOtherService(OtherService otherService) {
this.otherService = otherService;
}
}
现在,您必须同时配置了masterserviceinpl
和实现OtherService
的任何服务。有很多方法可以做到这一点,最流行的方法是在XML配置中显式地配置基于注释的配置,只需一秒钟
还要注意,如果不使用接口,AOP往往非常脆弱。在你的代码中,你的Impl实际上并没有实现任何东西。我建议您不要这样做。您能提供更多的代码和上下文吗?我无法理解你想做什么…@davetron5000我更新了我的问题,如果我这样调用方法,我会出错。请看我的更新