java 普通类调用Spring注解方式的Service层bean

注意:此篇只是给那些spring晕头者查阅,大神绕道

  • 我们在开发的时候肯定经常用到JUnit,
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" }) @Controller public 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;

【java 普通类调用Spring注解方式的Service层bean】这样装配了,但是报空指针,意思就是拿不到这个类:
(错误写法重现)
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" }) @Controller public 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); }}

    推荐阅读