Autowired bean is null in MVC Controller

I'm trying to autowire a bean in the MVC Controller class, but I can not get another value, than null. When I put throw new Error("E") in constructor of the bean to be injected into the helloWorldController bean, I get an Exception: Error creating bean with name helloWorldController: Injection of autowired dependencies failed. But when I run test without error in constructor, I don't get the bean, I get null.

I'm totally confused. What does it do? It is trying to create and inject a dependency, when it creates the controller instance. Ok, so why the variable is not inicialized, if error did not occured?

I have extended my post at the bidding of 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; } }

The bean implements any empty interface:

package testy.sprung.beany; public class AwiredBeanImpl implements AwiredBean { @Override public String toString() { return "CommonAutowired"; } public AwiredBeanImpl() { throw new Error("E"); } }

I run it inside the test. The test fails, because wether my error or NullPointerException is thrown:

@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/"); } @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()); } }

-------------Problems Reply------------

Instead of controller = new HelloWorldController(); you should inject your controller so that it becomes a Spring-managed bean.

Category:model view controller Views:1 Time:2011-07-04

Related post

  • @Autowired bean is null when referenced in the constructor of another bean 2011-06-13

    Shown below is a snippet of code where I try and reference my ApplicationProperties bean. When I reference it from the constructor it is null, but when referenced from another method it is fine. Up until now I have not had no problem using this autow

  • Json passed is null in MVC controller method 2012-02-23

    I am doing below to pass Json data to My MVC controller action Script var jInput = $("textarea"); var count = 0; var jsonPackage = "{"; $.each(jInput, function (i) { jInput[i].style.borderColor = ""; if (jInput[i].value != "") { if (count != 0) { jso

  • Autowired bean are not handled in my Controller bean (Spring-MVC) 2010-09-06

    I create a Controller bean to map a dedicated URI. web.xml file : <!-- Spring MVC Servlet (that will route HTTP requests to BlazeDS) --> <servlet> <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> <servlet-class

  • Spring MVC controller - getPathInfo() is null 2011-11-10

    I have worked servlet that need to convert to Spring MVC controller to have access spring beans etc. Why in normal servlet request.getPathInfo() return not null, but in Spring Controller i get null value ? I know i can use @PathVariable, but wonder w

  • Session object is null in ASP.NET MVC Controller 2009-05-20

    This is a strange problem because yesterday I was executing my code in Cassini (VS2008) and in the action method of the controller the Session object was valid and holding session data. Today I restarted VS2008 and opened the project and the Session

  • $.getJSON call with null parameters to MVC controller action 2009-09-10

    I have a controller with the following action code: public JsonResult CheckPasswordStrength(string password, string username, string firstname, string lastname) { ... return this.Json(jsonResponse); } Then in my javascript on page I call $.getJSON('h

  • What does it mean when Spring MVC @Controller returns null view name? 2011-07-29

    I downloaded the code for the Spring MVC 3 Showcase. One thing puzzles me (well, more than one), why does this (edited for concision) sample return null? @Controller @RequestMapping("/form") public class FormController { @RequestMapping(method=Reques

  • View keeps returning null to my controller in mvc 3 2012-04-02

    I'm trying to send data to the Controller from the View. I have a fairly complex object, which contains one array and one object with values. Whatever I try, it's null in my controller. I have inspected the data with IE9s F12, and the data is there.

  • Spring mvc controller issue 2011-01-15

    I'm trying to learn spring MVC, so far so good but I'm kind of stuck now. I'm trying to learn how to create json and get it with javascript(jquery). But for testing purposes I tried to create something just so I can see that is displayed properly tro

  • Autowired field remains null causing WicketRuntime Exception 2014-08-27

    There are tons of these questions but suggested solutions doesnt seem to work for me. Im useing wicket along with hibernate and spring. Im trying simple form with one textfield but wicket keeps complaining abou NullPointerException which comes from a

  • Cannot inject beans in servlet context to Controller 2014-11-24

    I have read Injecting Jaxb2Marshaller in Spring MVC controller and Difference between applicationContext.xml and spring-servlet.xml in Spring etc but feeling confused on why my case is not working. Here is what I have in my app contexts and web.xml (

  • How can I post an array of string to ASP.NET MVC Controller without a form? 2008-11-21

    I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids

  • Using Server in Mvc.Controller 2009-03-11

    I have my own inherited App.Controller from Mvc.Controller which then all of my controllers inherit from. I wrote a provider utilizing an interface and implemented it as MyService and the constructor takes the Server property of Mvc.Controller which

  • Best practice for removing Database calls from MVC Controller classes 2009-03-24

    I have an Action method in an ASP.NET MVC Controller class that handles form posts from a fairly basic "create/edit a user" page. I'm new to MVC so I've been following code samples from various Microsoft tutorials, this is how the method looks curren

  • JQuery - what is the best way to fire a MVC controller action via JQuery? 2009-05-08

    Basically, I have several Radio Buttons in a filtering column. For example, if I am in the \Catalog\Flooring\Harwood section I have Radio Buttons for [Area Rugs], [Carpet] & [Stone & Tile]. So, what I want to do, instead of embedding an tag u

  • Aop, Unity, Interceptors and ASP.NET MVC Controller Action Methods 2009-08-27

    Using log4net we would like to log all calls to our ASP.NET MVC controller action methods. The logs should include information about any parameters that were passed to the controller. Rather than hand-coding this in each action method we hope to use

  • Should an MVC Controller and View have a 1 to 1 relationship? 2009-11-04

    I am currently using asp.NET MVC to build a Content Management System parts of a website and have the odious job of recreating all of my Views as Partial Views as it appears to be breaking the way the site map works. For example, my FAQAdminControlle

  • ASP.NET MVC Controller Lifecycle 2009-11-19

    It's my understanding that the constructor for a controller is not called during each web request. Assuming this is true, what is the lifecycle of a controller? Is is "constructed" upon app start, then cached and invoked with the requestcontext injec

  • Sending String Data to MVC Controller using jQuery $.ajax() and $.post() 2009-12-03

    There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried: $.pos

Copyright (C), All Rights Reserved.

processed in 0.120 (s). 11 q(s)