我正在尝试在MVC Controller类中自动装配一个bean,但是我无法获得另一个值,而不是null。当我将throw new Error("E")
放入要注入helloWorldController
bean的bean的构造函数中时,我得到一个异常:创建名为helloWorldController的bean时出错:注入自动连接的依赖项失败。但是当我在构造函数中运行没有错误的测试时,我没有得到bean,我得到null。
我完全糊涂了。它有什么作用?它在创建控制器实例时尝试创建并注入依赖项。好吧,那么为什么变量没有被反复化,如果没有发生错误呢?
我在Sean Patrick Floyd的竞标中延长了我的职位:
package testy.sprung; //import declarations ommited import testy.sprung.beany.AwiredBean; @Controller public class HelloWorldController { private Logger log = Logger.getLogger("springTestLogger"); @Autowired private AwiredBean oz; @RequestMapping("/sprung") public ModelAndView base() { log.debug("base URI"); ModelAndView mv = new ModelAndView(); mv.setViewName("firstPage"); return mv; } @RequestMapping(value="/{articel}/{subTitle}",method=RequestMethod.GET) public ModelAndView szia(@PathVariable("articel") String articel, @PathVariable("subTitle") String st, @RequestParam(value="co", required=false) String co) { log.debug("Path GET/{articel}/{subtitle}: " + articel + "/" + st + "?co=" + co); ModelAndView mv = new ModelAndView(); mv.setViewName("index"); // now put index.jsp in /WEB-INF/files mv.addObject("articel", articel); mv.addObject("subtl", st); mv.addObject("co", co); mv.addObject("awir", oz); //but it is null return mv; } }
bean实现任何空接口:
package testy.sprung.beany; public class AwiredBeanImpl implements AwiredBean { @Override public String toString() { return "CommonAutowired"; } public AwiredBeanImpl() { throw new Error("E"); } }
我在测试中运行它。测试失败,因为我的错误或NullPointerException
被抛出:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:WebContent/WEB-INF/sprung-servlet.xml") public class ZakladniExtendedTest extends TestCase { private MockHttpServletRequest request; private MockHttpServletResponse response; private HelloWorldController controller; @Inject private ApplicationContext context; public ZakladniExtendedTest() { PropertyConfigurator.configure("t-resources/log4j.properties"); } @Before //this method is called before each test public void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); controller = new HelloWorldController(); } @Test public void testThemeResolverExists() { //this test works assertTrue(context.containsBean("themeResolver")); } @Test public void autowiringTest() throws Exception { //but this not request.setRequestURI("/title/subtitle"); request.setMethod("GET"); request.setParameter("co", "param"); ModelAndView mav = new AnnotationMethodHandlerAdapter().handle(request, response, controller); String viewName = mav.getViewName(); Map objects = mav.getModel(); assertEquals("index", viewName); //NullPointerException follows: assertEquals("CommonAutowired", objects.get("awir").toString()); } }
答案 0 :(得分:8)
而不是controller = new HelloWorldController();
你应该注入你的控制器,使它成为一个Spring管理的bean。