美文网首页
junit测试spring注入的两种方法

junit测试spring注入的两种方法

作者: huangxiongbiao | 来源:发表于2017-06-27 12:33 被阅读525次

方法一:
加载

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

}

相关文章

网友评论

      本文标题:junit测试spring注入的两种方法

      本文链接:https://www.haomeiwen.com/subject/wkfecxtx.html