首页 > 解决方案 > 如何从spring boot服务层调用java类方法

问题描述

我有我的 Spring Boot 应用程序,我试图从我的应用程序之外的不同模块中的 java 类调用方法。我已将依赖项添加到该外部模块的项目 pom 中。外部模块不是 Spring Boot 应用程序。我的代码如下

@Service
public class MyServiceImpl {
    private MyInterface myInterface;
    
    public Response callMethod1() {
        Response response = new Response();
        response = myInterface.callMethod1();
        return response;
    }
}

接口 MyInterface 及其实现是外部模块的一部分。代码是这样的。

public interface MyInterface {
    Response callMethod1();
}

执行:

public class InterfaceImpl implements MyInterface {
    Response callMethod1() {
        Response response = doSomething();
        return response;
    }
}

当我调用服务方法时,我看到它因 InvocationTargetException 而失败。我在 Eclipse 中尝试了调试器,但我不会看到实现中的断点被击中。我尝试将接口和实现的代码移动到我的项目中,并进行一些修改,看看我是否可以让它工作。这是我的更改。

服务等级:

@Service
public class MyServiceImpl {
    @Autowired
    private MyInterface myInterface;
    
    public Response callMethod1() {
        Response response = new Response();
        response = myInterface.callMethod1();
        return response;
    }
}

界面:

public interface MyInterface {
    Response callMethod1();
}

执行:

@Service
public class InterfaceImpl implements MyInterface {
    Response callMethod1() {
        Response response = doSomething();
        return response;
    }
}

如何在不更改实现并将其保留在其原始模块中的情况下调用 java 类方法。

谢谢。

标签: javaspring-boot

解决方案


@Configuration
public class Config {
    
    @Bean
    public Foo createFoo() {
        Foo foo = new Foo();    // this is POJO
        return foo; // after return it will be saved in Spring Context and become a Bean 
    } 

}

推荐阅读