首页 > 解决方案 > 从另一个包调用的函数无法访问参数

问题描述

这是我的问题:

我有两个类:A 类包含一些@Value("${param.username}")@Value("${param.password}"),我有一个使用这两个参数的函数,我@GetMapping(path = "/functionA")用于运行 functionA (此函数是对服务器进行身份验证的 Post 请求)

用户名和密码已开启application-contextual-values.properties

当我在浏览器上运行时localhost:8080/app/functionA=> 它可以工作!

我有另一个类 B,在另一个包 B 上,我想调用第一个类 A 并使用 fuctionA 进行身份验证。=> 我有一个错误:Username must not be null

这意味着我无法获取username并且password存储在application-contextual-values文件中。

这是我的 A 类代码:

public class A {

    @Value("${param.username}")
    private String username;

    @Value("${param.password}")
    private String password;

    @GetMapping(path = "functionA")
    public AuthentificationModel getClient() {
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(this.username, this.password);
        String jwt = getJWT(); <======  this function is also in this class A
        
        ...
     
        I'm doing a construction of params, to send on POST 

        return token;
     }

AuthentificationModel 正是 POST 请求后发回的内容(access_token、client_id、token_type)

我的 B 类是:

import fr.ag2rlamondiale.ytb.rest.A; <==== class A

public class B {

   private static Map<String, String> getRequestHeader() {

       Map<String, String> requestHeaders = new HashMap<>();
       try{
         final A objA = new A(); <===== instance of my class A here
           String token = objA.getClient().getAccessToken(); <==== getClient() is the funct that returns token on class A

           requestHeaders.put("Authorization", "Bearer ", + token); 
             
           ... many other put for header
         } catch (CommonException e) {
        e.printStackTrace();
    }
    return requestHeaders;
}

我的 application-contextual-values.properties :

param.username="kljkjsdf555sdf"
param.password="xxx222xxx"

是因为我需要使用参数用户名和密码在 A 类上添加构造函数吗?使它在我的上下文中工作的正确方法是什么?

编辑 :

在 AI 类中添加:@Controller

在 B 类中:我添加了@Authowired A objA,没有new A();

但是现在,有一个新的错误:Cannot make a static reference to the non-static field objA

意思是类 A 上的元素是非静态的,我使用 objA 作为静态对象?

标签: javaspringrest

解决方案


使用依赖注入和@Autowired 你的A实例,B不要A在你的B类中创建新的实例。


推荐阅读