为什么在java中使用 @Value("${alipay.publicKey}") 就会报错呢?

我在配置xml文件中写了一些资源,但是在控制层直接调用时,就会启动报错。

在单独的一个类中调用它,然后,再用控制层调用这个类中的,配置文件就可以。 这个类中的写法和控制层基本上是一样的。

控制层的

 //公钥
    @Value("${alipay.publicKey}")
    public String publicKey;

会报错

下面是常量类的写法

package com.hnsaturn.saturn005.constant;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 项目初始化 常量类
 * */
@Component
public class ProjectInit implements ApplicationRunner {

    //应用id
    @Value("${alipay.appId}")
    public String appId;

    //私钥
    @Value("${alipay.privateKey}")
    public String privateKey;

    //公钥
    @Value("${alipay.publicKey}")
    public String publicKey;

    //支付宝网关
    @Value("${alipay.gateway}")
    public String gateway;

    //支付成功后的接口回调地址,不是回调的友好页面,不要弄混了
    @Value("${alipay.notifyUrl}")
    public String notifyUrl;

    /**
     *  项目初始化事件
     * */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化支付宝SDK
        Factory.setOptions(getOptions());
        System.out.println("**********支付宝SDK初始化完成**********");
    }

    private Config getOptions() {
        //这里省略了一些不必要的配置,可参考文档的说明

        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = this.gateway;
        config.signType = "RSA2";
        config.appId = this.appId;

        // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = this.privateKey;

        //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = this.publicKey;

        //可设置异步通知接收服务地址(可选)
        config.notifyUrl = notifyUrl;

        return config;
    }
}


下面是报错信息


Parameter 2 of constructor in com.hnsaturn.saturn005.controller.PayController required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

@AllArgsConstructor默认无参构造,你给加个这玩意就变有参了,你有成员变量,就需要给成员变量值,但是这个时候还没有注入呢,所以不行,去掉这个就可以了,大概就这么个意思

报错是 PayController 构造方法有一个 String 类型的参数,Spring 无法找到这个参数对应的 bean ,因此无法实例化 PayController,检查下 PayController 构造方法吧,和 ProjectInit 没关系。如果还有疑问可以贴下 PayController 的构造方法代码。

img


去掉

@RequestParam(required = true) String subject,问题在这里吧,这里设置必须传值,但是没设置默认值;defaultValue