Spring 工作加载时初始化静态对象

创建一个系统配置对象,而配置内容一般为静态变量,spring 实现静态变量在系统启动初始化的时候,初始化静态变量。

第一步 :声明该配置对象为bean ,这样spring工程启动时便会加载该对象。

xml形式

<bean id="role" class="spring.chapter2.maryGame.Role"/>

第二步:创建静态对象

public class SystemConfig{

@Resource

private SystemConfigService systemConfigService ;// 声明系统service,通过数据库读取系统配置

private static SystemConfigService systemConfigService_static ; // 声明静态service接口

private static List<Map<String,Object>> systemInfo = null; // 存取系统信息

扫描二维码关注公众号,回复: 3556795 查看本文章

/*

* 被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

* 这里初始化静态变量不能使用static{}静态块,因为静态块执行是先@Resource注入Service之前,这个时候Service还没有被加载,汇报NullPoint异常

*/

@PostConstruct

public void init(){

systemConfigService_static = systemConfigService ; //将Service赋值给静态变量

systemInfo = systemConfigService_static .getSystemInfo();

}

}

猜你喜欢

转载自blog.csdn.net/qq_26462567/article/details/82969793