java如何启动时定义并初始化一个全局变量(内存中)
前言
java如何启动时定义并初始化一个全局变量(内存中),项目启动时,通过读取配置文件来构建一个实体类对象,然后在之后可以直接使用,而不是每次使用都要进行构建
前置准备
实体类结构
package cn.daenx.demo;
import lombok.Data;
@Data
public class Person {
private String info;
}
配置文件
spring:
profiles:
active: dev
test:
name: daen
age: 18
方式一
新建一个类
package cn.daenx.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class MyTestCom {
private static String name;
private static Integer age;
@Value("${test.name}")
public void setName(String name) {
MyTestCom.name = name;
}
@Value("${test.age}")
public void setAge(Integer age) {
MyTestCom.age = age;
}
@Bean
public Person doInit() {
Person person = new Person();
System.out.println("@Bean初始化");
person.setInfo("姓名:" + name + ",年龄:" + age);
return person;
}
}
使用
package cn.daenx.demo.controller;
import cn.daenx.demo.Person;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/test")
public class TestController {
@Resource
private Person person;
@GetMapping(value = "/02")
@ResponseBody
private String req02() {
System.out.println("02");
return person.getInfo();
}
}
方式二
新建一个类
package cn.daenx.demo;
public class GlobalInfo {
private static Person person;
public static Person getPerson() {
return person;
}
public static void setPerson(Person person) {
GlobalInfo.person = person;
}
}
新建一个实体类,并实现ApplicationRunner
package cn.daenx.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunImpl implements ApplicationRunner {
@Value("${test.name}")
private String name;
@Value("${test.age}")
private Integer age;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner初始化");
Person person = new Person();
person.setInfo("姓名:"+name + ",年龄:" + age);
GlobalInfo.setPerson(person);
}
}
使用
package cn.daenx.demo.controller;
import cn.daenx.demo.Person;
import cn.daenx.demo.GlobalInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping(value = "/01")
@ResponseBody
private String req01() {
System.out.println("01");
return GlobalInfo.getPerson().getInfo();
}
}