1. 程式人生 > >多個java檔案共用同一動態變數的兩種方法

多個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—>