spring mvc在非Controller类无法使用Service bean解决方案
来源:互联网 发布:xmlbar软件下载 编辑:程序博客网 时间:2024/05/17 21:47
1、思路
因为不是在@Controller类中,使用@Autowired注解是得不到Service类的,所以可以通过手动方式进行获取。
2、配置(如果已经配置好了,并且能在@Controller中获得service类可以跳过这个)
为了更好的区分,所以spring mvc的xml配置进行了分层,每个目录管理每个层次的东西,层次分明。
在web.xml文件中配置srping的上线文。
在springmvc.xml中配置控制层的扫描
在applicationContext-service.xml中配置service的配置
配置好了的话在正常情况下使用@Controller、@RequestMapping进行说明,配合使用@Autowired注解说明这个service类,就可以获得该类进行使用。
3、在非Controller类无法使用Service
由于不是在Controller类,所以使用@Autowired注解说明这个service类是没有用的,无法获取这个类,这个类还是null。
(1)首先在web.xml文件中配置一个监听,启动的时候就运行这个监听
- 1
- 2
- 3
- 4
- 5
- 6
(2)SpringInit类(这个类的目的是获取这个类的对象,为后续获取Service做准备)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
(3)假设我要在一个非Controller类中获取service类
只需要在改类或需要调用该类的方法中加入这段代码:
- 1
解释:
(1)AppCdService appcdService
是我需要的Service类,就相当@Autowired注解是需要的类,需要用我需要的类进行接收
(2)SpringInit.getApplicationContext().getBean(“AppCdService”)
SpringInit这个是监听类的名称,需要导入这个类相关包,
getApplicationContext()是这个类的方法
getBean(“AppCdService”)是获取Bean方法,其中AppCdService是applicationContext-service.xml中配置的中的id名称,代表想取出那个Service进行注解。最后进行强转为该Service。期间需要注意配置需要配对
- spring mvc在非Controller类无法使用Service bean解决方案
- spring mvc在非Controller类无法使用Service bean解决方案
- 在spring-mvc的非controller类里面调用service方法
- spring mvc 无法扫描jar中controller和Service
- Spring MVC不要在@Service bean中保存状态
- spring mvc Controller中使用@Value无法获取属性值
- spring mvc Controller中使用@Value无法获取属性值
- Spring MVC @Autowired、@Controller、@Service 的实现
- Spring中用@Component、@Repository、@Service和 @Controller等标注的默认Bean名称会是小写开头的非限定类名
- spring-mvc 非 controller 层获取HttpServletRequest
- 使用Spring MVC 在controller里如何跳转,传参数
- 在非controller里调用service
- (亲测有效。)Spring MVC中,Controller中使用service只需使用注解,但是普通类获取 service或 dao 都是null空的。
- Spring MVC中@Repository、@Service、@Controller、@Compon的使用及区别
- Spring MVC中一般类使用service
- Spring MVC中一般类使用service
- Spring mvc (五) [ControllerClassNameHandlerMapping根据Controller类名匹配,解决了bean的递增配置问题]
- Spring mvc Ambiguous mapping found. Cannot map controller bean method
- Python学习手册 第十四章习题抄写
- 数据结构实验之二叉树七:叶子问题
- Visual studio 无限重启
- linux下nmap的安装
- UVa1218
- spring mvc在非Controller类无法使用Service bean解决方案
- 为什么fork调用会返回两次
- windows下tomcat运行时出现java.io.IOException: 您的主机中的软件中止了一个已建立的连接
- RESTful API 特点
- 表单验证
- ESP8266常用脚本命令之一
- Keras classifier分类(二)
- 改变一个list<Map<String,Object>>,并给他重新赋值,不能使用新循环,要使用旧循环
- 算法设计与分析——棋盘覆盖问题