java 普通类调用Spring注解方式的Service层bean
来源:互联网 发布:大神,我养你网络 番外 编辑:程序博客网 时间:2024/04/30 06:01
注意:此篇只是给那些spring晕头者查阅,大神绕道
- 我们在开发的时候肯定经常用到JUnit,
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" })@Controllerpublic class TestUserService { private static final Logger LOGGER = Logger.getLogger(TestUserService.class); @Autowired private UserInfoService userInfoService; private static ClassPathXmlApplicationContext ctx; @Test public void save() { UserInfo userInfo = new UserInfo(); userInfo.setName("杨成"); userInfo.setAge(23); userInfo.setTelephone("13212221333"); userInfoService.saveOrUpdate(userInfo); }}
- 上面调用spring管理的bean(Service层)是可以的,但是我们自己用main函数来调用:
@Autowired private UserInfoService userInfoService;
这样装配了,但是报空指针,意思就是拿不到这个类:
(错误写法重现)
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" })@Controllerpublic class TestUserService { private static final Logger LOGGER = Logger.getLogger(TestUserService.class); @Autowired private static UserInfoService userInfoService; public static void main(String[] args) { UserInfo userInfo = new UserInfo(); userInfo.setName("杨成1"); userInfo.setAge(23); userInfo.setTelephone("13212221333"); userInfoService.saveOrUpdate(userInfo); }}
- 当然了解spring和会用spring的人都会觉得我这样的写法很不可思议(基本不适合搞程序这行了),但是不乏有很多人这样去写。
我们看到Junit是需要先加载spring然后才做调用,我们用spring管理的bean是不是需要先加载spring呢?肯定的啊!所以正确姿势如下:
public class TestUserService { private static final Logger LOGGER = Logger.getLogger(TestUserService.class); private static ClassPathXmlApplicationContext ctx; public static void main(String[] args) { ctx = new ClassPathXmlApplicationContext( new String[] { "classpath:spring.xml", "classpath:spring-hibernate.xml" }); UserInfoService userInfoServiceImpl = ctx.getBean(UserInfoService.class); UserInfo userInfo = new UserInfo(); userInfo.setName("杨成1"); userInfo.setAge(23); userInfo.setTelephone("13212221333"); userInfoServiceImpl.saveOrUpdate(userInfo); }}
0 0
- java 普通类调用Spring注解方式的Service层bean
- 普通java类调用spring注解bean
- Spring Boot 普通类调用Bean对象的一种方式
- Java后台代码调用Spring的@Service Bean的方式
- java 普通类调用spring bean对象
- Spring 注解中,普通类获取@Service标记的方法 或者bean对象
- spring基于注解的普通类怎么调用@Services注解的service方法
- spring基于注解的普通类怎么调用@Services注解的service方法
- Spring框架中普通的类如何调用注解Service中的方法
- 普通Java类获取Spring的bean
- 普通Java类获取Spring的bean
- Spring Boot普通类调用bean
- Spring Boot普通类调用bean
- 普通类调用Spring bean对象
- spring boot普通类调用bean实现
- Spring Boot普通类调用bean
- Spring的XML配置的bean调用注解方式的bean
- 普通Java类获取Spring的Bean的方法
- AndroidStudio 使用SVN
- 运行Spark程序
- 遇到的问题笔记以及解决方案【长期更新】
- ext form自适应windows
- 线程池
- java 普通类调用Spring注解方式的Service层bean
- 2693 上学路线(施工)
- 【C++】c++中的继承
- 小波变换和motion信号处理(一)
- 异常:部署在myeclipse 时。jdk版 Unsupported major.minor version 51.0 (unable to load class com.admin.AdminCo
- php 解决undefined function curl_init()问题 64位window
- 使用@media媒体查询实现多设备字体图片自适应
- [Leetcode] #300 Longest Increasing Subsequence
- 判断数组是否为搜索二叉树的后序遍历