前言:
以前小白的我总是困惑两个java文件如何共用一个动态变量,今天就做一个总结
方法一:
package com.Business.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Business.domain.Hui;
@RestController
public class WebController {
@Autowired
private Hui hui;
@RequestMapping("/index")
public String index1(){
return hui.getName()+"--->";
}
}
package com.Business.order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.Business.domain.Hui;
@Component
@Order(1)
public class Task implements CommandLineRunner {
@Autowired
private Hui hui;
public void run(String... args) {
hui.setName("qianming");
System.out.println(hui.getName() + "--->");
}
}
package com.Business.domain;
import org.springframework.stereotype.Component;
@Component
public class Hui {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
方法二:
package com.Business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Business.utils.Constant;
@RestController
public class WebController {
@RequestMapping("/index")
public String index1(){
return Constant.QUERY_INDEX_TYPE_ALL+"--->";
}
}
package com.Business.order;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.Business.utils.Constant;
@Component
@Order(1)
public class Task implements CommandLineRunner {
public void run(String... args) {
String hehe = "qianming";
Constant.QUERY_INDEX_TYPE_ALL = hehe;
System.out.println(Constant.QUERY_INDEX_TYPE_ALL+"--->");
}
}
package com.Business.utils;
public class Constant
{
public static String QUERY_INDEX_TYPE_ALL = "typeAll";
public static final String QUERY_SORT_ORDER_ASC = "asc";
}
以上两种方法都这样执行:
运行spring boot程序控制台打印为:
qianming—>
浏览器输入http://localhost:8080/index:
qianming—>