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;

这样装配了,但是报空指针,意思就是拿不到这个类:
(错误写法重现)

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

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术杨工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值