多个java文件共用同一动态变量的两种方法

前言:

以前小白的我总是困惑两个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—>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小强签名设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值