2

我有以下内容:

@Service(DropboxService.NAME)
public class DropboxServiceBean implements DropboxService {

    @Inject
    private CustomConfig customConfig;


    private final String ACCESS_TOKEN = customConfig.getDropboxAppToken();
    DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial", "en_US");
    DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);

有谁知道我如何才能customConfig.getDropboxAppToken();首先加载的值。我不断收到以下错误:

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myApp_DropboxService' defined in URL
[jar:file:/E:/Cuba/myApp/deploy/tomcat/webapps/app-core/WEB-INF/lib/app-core-0.1-SNAPSHOT.jar!/com/daryn/myApp/service/DropboxServiceBean.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.daryn.myapp.service.DropboxServiceBean]: Constructor
threw exception; nested exception is java.lang.NullPointerException

我正在尝试的当前代码

错误:创建名为“ecosmart_BackupService”的 bean 时出错:通过字段“dropboxService”表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“ecosmart_DropboxService”的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.NullPointerException

@Service(DropboxService.NAME)
public class DropboxServiceBean implements DropboxService {

    @Inject
    private CustomConfig customConfig;


    private String ACCESS_TOKEN = "";
    DbxRequestConfig config;
    DbxClientV2 client;



    @PostConstruct
    public void postConstruct() {
        System.out.println("**************Running post construct");
        ACCESS_TOKEN = customConfig.getDropboxAppToken();
        config = new DbxRequestConfig("dropbox/java-tutorial", "en_US");
        client = new DbxClientV2(config, ACCESS_TOKEN);
    }
4

2 回答 2

1

Spring 仅在构造对象之后才注入字段,并且在您的情况下ACCESS_TOKEN甚至在此之前初始化。

您需要创建一个构造函数并将 bean 注入到构造函数中,如下所示:

@Inject
public DropboxServiceBean(CustomConfig customConfig) {
  this.customConfig = customConfig;
  ACCESS_TOKEN = customConfig.getDropboxAppToken();
}
于 2017-09-19T05:52:52.700 回答
-1

好吧,经过一番折腾,这是我很好的解决方案。我不知道为什么 CustomConfig 不会首先初始化...

@Service(DropboxService.NAME)
public class DropboxServiceBean implements DropboxService {        


    @Inject
    private CustomConfig customConfig;


    private String ACCESS_TOKEN = "";
    DbxRequestConfig config =new DbxRequestConfig("dropbox/java-tutorial", "en_US");
    DbxClientV2 client;

    public static boolean isInitiated = false;

    public void generateDbxClient(){
        ACCESS_TOKEN = customConfig.getDropboxAppToken();
        client = new DbxClientV2(config, ACCESS_TOKEN);
    }

    @Override
    @Transactional
    public void uploadFile(FileDescriptorExt file, String path) {

        if(isInitiated==false){
            System.out.println("generating client");
            generateDbxClient();
            isInitiated=true;
        }
于 2017-09-19T07:54:24.560 回答