java - 从另一个包调用的函数无法访问参数
问题描述
这是我的问题:
我有两个类: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 作为静态对象?
解决方案
使用依赖注入和@Autowired 你的A
实例,B
不要A
在你的B
类中创建新的实例。
推荐阅读
- sorting - 有没有一种简单的方法可以按值和键(Kotlin)对 HashMap 进行排序?
- python - 如何在python中使用多个for循环保存为列表
- java - 如何解决找不到工件org.eclipse.rcptt.extensions.ecl:parent:pom:2.3.0-SNAPSHOT
- java - 错误:在类中找不到主方法,请将主方法定义为:public static void main(String[] args)
- python - 创建数据框 Pandas 时如何将数字保留为字符串
- flutter - Flutter:如何在底部导航栏后面显示内容
- flutter - 将用户事件和时间与日历上的选定日期映射
- javascript - 如何从 Farbic.js 获取特定对象并读取类型
- c - C语言用户定义函数定义错误
- python - else语句中字符串的整数输入(Python)