0
点赞
收藏
分享

微信扫一扫

spring mvc 工具类的静态方法使用注入


类代码

@Component
public class RegisterConfig

@Autowired
private DepartMentService departMentService;

public void setDepartMentService(DepartMentService departMentService) {
this.departMentService = departMentService;
}

private static RegisterConfig registerConfig;

@PostConstruct
public void init(){
registerConfig = this;
registerConfig.departMentService = this.departMentService;
}

public static String RootPath = System.getProperty("register.webapp");


public static int DepartMentIDLength(){
if(departMentIDLength == 0){
departMentIDLength = registerConfig.departMentService.departMentUnitIDLength();
}
return departMentIDLength;
}

private static int departMentIDLength = 0;

其中:@Component, @PostConstruct 还有private static RegisterConfig registerConfig;是关键,原理应该是容器启动时实例化了RegisterConfig ,注入了departMentService,调用了init(),并将RegisterConfig.registerConfig初始化,然后就可以使用了。

因application.xml中的xml配置为 default-lazy-init=”true” ,所以要在这个配置文件中加入一个配置,让RegisterConfig 可以在容器启动时就注入。

<beans>
<bean id="registerConfig" class="com.register.normalClass.RegisterConfig" init-method="init"
lazy-init="false">
</bean>
</beans>```

注:
这样处理后是可以注入了,但是这个类中的一个读取根目录的变量却读取不到了,System.getProperty读到的是null

public static String RootPath = System.getProperty("register.webapp");

这就需要在启动监听里设置一下这个值:

.RootPath = System.getProperty("register.webapp");

如果哪位有更好的方法,请在评论里给一下,谢谢


举报

相关推荐

0 条评论