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

来源:互联网 发布:淘宝手机怎么下架宝贝 编辑:程序博客网 时间:2024/05/16 18:32

类代码

@Componentpublic 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");

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

   //RegisterConfig加了静态注入后,这个值就取不到了,所有在这个地方给他赋值                RegisterConfig.RootPath = System.getProperty("register.webapp");

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

0 0
原创粉丝点击