SpringMVC静态方法中如何注入service非静态方法,如何在contextInitialized之前注入bean,使service不会报空
2018-03-07 20:54
1056 查看
1.静态方法中不能用非静态方法 首先声明java中只有静态方法和静态参数,没有静态类。但可以在类中将自己声明称静态参数,从而模拟将整个类都静态加载在缓存中,具体下面再详细讲。 因为静态方法在程序启动时就加载,而非静态方法此时还不在内存中(spring中加@controller等注解的话spring帮你实例化,否则都要new 出来实例化),所以无法使用非静态方法。而有时静态方法中需要使用@Resource注入的service,该怎么做呢。 解决方法如下:public class DictUtil {@Resourceprivate DictService dictService; //引入serviceprivate static DictUtil dictUtil; //关键一:将类自己作为静态参数声明public void setTestService(DictService dictService) { //给service加set方法this.dictService = dictService;}@PostConstruct //关键二 通过@PostConstruct 实现初始化和销毁bean之前进行的操作public void init() {dictUtil = this;dictUtil.dictService = this.dictService; // 初使化时将已静态化的Service实例化}} 首先引入service--再将类自己作为静态参数声明--给service加set方法--@PostConstruct后将类设为自己。就可以用了。 2.如果在contextInitialized中就要加载静态工具类,有时会报service为空。 程序启动时会加载web.xml文件,加载顺序是context-param->listener->filter->servlet; 要注意Spring在servlet阶段才会扫描controller和service等。 但contextInitialized为servletContextListener的实现方法,所以属于listener,在servlet之前就执行了。所以找不到service,因为此时spring还没开始扫描service呢。 但我们可以看到context-param是最开始执行的。所以我们应该将service在context-param的阶段就注入进去。 一般context-param是加载applicationContext用的,所以在applicationContext中是加载jdbc等 在Mybatis中applicationContext可以扫描mapper。在这里我们把controller,service,dao都先扫描进spring中。然后在spring-mvc中继续扫描一遍,因为貌似spring-mvc中需要扫描controller. 这样的话service就不会报空了
相关文章推荐
- 静态方法注入bean
- SpringContextHolder 静态持有SpringContext的引用(如何取得Spring管理的bean )
- 静态方法调用注入对象(springMvc)
- springmvc 自动注入静态service 解决方案
- web.xml中session监听调用springmvc注入的service方法
- 静态工具类中使用注解注入service(静态方法调用有注解的非静态方法)
- spring注入bean进入工具类的静态方法
- 在工具类静态方法调用@Autowired注入的bean方法
- Spring 无法注入静态变量,直接在静态方法中获取bean
- spring项目中静态方法中使用注入的bean
- Spring中不用注入如何正确调用service方法
- 如何使用springmvc框架在普通的servlet注入service
- spring注入时bean的set方法为什么不能是static类型的?(为什么要用单例模式而不是静态方法)
- 使用Spring注解,在静态方法中注入bean
- springMVC通过getBean()获取context.xml文件中定义的service接口类
- Android Context的startService方法如何使用?
- 报错 BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext 的解决方法
- 静态工厂方法和实例工厂方法注入bean
- hadoop超时解决办法context.progress()的作用 假设在map()方法中,你有一个从数据库读取大量数据的操作,是用一个循环来完成的,并且,在读完全部的数据之前,你不会有任何的数据输出
- 面试题--如何防止sql注入,使用PreparedStatement的预编译,传入的内容就不会和原来的语句发生任何匹配的关系,达到防止注入的方法