junit测试spring注入的两种方法

2017-06-27  本文已影响525人  huangxiongbiao

方法一:
加载

package spring;

import static org.junit.Assert.*;

import com.spring.model.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.manager.UserManager;

public class UserTest {

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml");
        UserManager mgr = context.getBean("mgr", UserManager.class);
        com.spring.model.User u = new User("name","123");
        mgr.save(u);
    }

}

方法二:
扫描注入加载

import static org.junit.Assert.*;

import javax.jws.soap.SOAPBinding.Use;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.spring.dao.entity.User;
import com.spring.service.UserService;
import com.spring.service.Impl.UserServiceImpl;


//指定bean注入的配置文件  
@ContextConfiguration(locations = "classpath:beans.xml") 
@RunWith(SpringJUnit4ClassRunner.class)  
public class TestUser {

    @Autowired
    private UserService userService;
    
    @Test
    public void test() {
        
        System.out.println(userService);
//      ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//      userService = ctx.getBean(UserServiceImpl.class);
        System.out.println(userService);
        User user = new User("wangjian","123145");
        userService.save(user);
    }

}

上一篇下一篇

猜你喜欢

热点阅读