Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: Annotation and xml based comtrollers in one application

  1. #1
    Join Date
    Aug 2008
    Location
    odessa.ua
    Posts
    26

    Default Annotation and xml based comtrollers in one application

    Is it possible to hold both annotation and xml based controllers in one application? How to do this?

    thanks

  2. #2
    Join Date
    Feb 2006
    Posts
    23

    Default

    I haven't tried this with controllers, but for example MDP Messagelistener and related classes work just fine.

    I have MDP MEssage listener and few message handler classes defined in xml file. Then helper and service classes are annotated with @Component. in xml file I have <context:component-scan> tag.

    After this I can set dependencies using @Resource annotation or setters and xml properties.

  3. #3
    Join Date
    Aug 2008
    Location
    odessa.ua
    Posts
    26

    Default

    is there easier way?

  4. #4
    Join Date
    Feb 2006
    Posts
    23

    Default

    I can't see how it could be easier? You can choose whether you want to define bean in xml file or by using annotation.

  5. #5
    Join Date
    Aug 2008
    Location
    odessa.ua
    Posts
    26

    Default

    t1589 thank you

  6. #6

    Default

    Yes, I've done it with Spring 2.5

    I didnt have to do anything special, just configure what you like with XML and annotations, should work

  7. #7
    Join Date
    Mar 2009
    Posts
    2

    Thumbs up

    I had no problem using the component scanning, this is really helpful to get rid of all this overconfiguration.

    The disadvantage is that there is a lot of people using the "classic" xml method, so the support is quite low or confusing if you need the annotation approach.

    Yann

  8. #8
    Join Date
    Aug 2010
    Posts
    3

    Default

    This is my attempt to have both Annotation and xml based controllers in one application. I started with SpringMVC version 2.5 step-by-step tutorial v. This was XML based controller. I was able to successfully deploy this web application. This app has two views hello.htm and priceincrease.htm. I retained the hello.htm as it is (i.e. XML based controller) and modified the priceincrease.htm to Annotation based. I was able to compile and deploy successfully these approaches together. However, I am encountering a strange issue: Now my application is unable to find mapping for "hello.htm" but "priceincrease.htm" works fine.

    Here are some modifications I did (I have retained code in form of comments which were applicable for XML based controller. Also for some reason Validator wasn't working so I have commented this code...pls ignore that for now.):
    Code:
    //public class PriceIncreaseFormController extends SimpleFormController {
    @Controller
    @RequestMapping("/priceincrease.htm")
    public class PriceIncreaseFormController{
        /** Logger for this class and subclasses */
        protected final Log logger = LogFactory.getLog(getClass());
    
        @Autowired
        private ProductManager productManager;
       //@Autowired
       // private Validator priceValidator;
        
       // public ModelAndView onSubmit(Object command) throws ServletException {
        @RequestMapping(method=RequestMethod.POST)
          public String processSubmit(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease,
        		  						BindingResult result, SessionStatus status){
            
        	//priceValidator.validate(priceIncrease, result);
        	
        	//if(result.hasErrors()){
        		//return "priceincrease"; // return the view name
        	//} else {
        		int increase = priceIncrease.getPercentage();
            	logger.info("Increasing prices by " + increase + "%.");
    	    	productManager.increasePrice(increase);
    	    	status.setComplete();
    	        //logger.info("returning from PriceIncreaseForm view to " + getSuccessView());	
    	        //return new ModelAndView(new RedirectView(getSuccessView()));
    	    	return "redirect:hello.htm";
        	//}
        }
    
        @RequestMapping(method=RequestMethod.GET)
        public String setupForm(@RequestParam(required = false, value= "20") Integer percentage, ModelMap model){
        //protected Object formBackingObject(HttpServletRequest request) throws ServletException {
            PriceIncrease priceIncrease = new PriceIncrease();
            priceIncrease.setPercentage(20);
            model.addAttribute("priceIncrease", priceIncrease);
            return "priceincrease";
        }
    
        public void setProductManager(ProductManager productManager) {
            this.productManager = productManager;
        }
    
        public ProductManager getProductManager() {
            return productManager;
        }
    
    }
    and the springapp-servlet.xml looks like
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
           
          	
    	
    	
      <!-- the application context definition for the springapp DispatcherServlet -->
        
        <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
            <property name="basename" value="messages"/>
        </bean>
        
    
      <bean name="/hello.htm" class="springapp.web.InventoryController">
      	<property name="productManager" ref="productManager" />
      </bean>
      
      <!--  Commented this as now the Annotations-based approach takes care of this
    
      <bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController">
            <property name="sessionForm" value="true"/>
            <property name="commandName" value="priceIncrease"/>
            <property name="commandClass" value="springapp.service.PriceIncrease"/>
            <property name="validator">
                <bean class="springapp.service.PriceIncreaseValidator"/>
            </property>
            <property name="formView" value="priceincrease"/>
            <property name="successView" value="hello.htm"/>
            <property name="productManager" ref="productManager"/>
       </bean>
       -->
    
       <bean name="/addproducts.htm" class="springapp.web.AddNewProductFormController">
    	   	<property name="sessionForm" value="true"/>
    	   	<property name="commandName" value="addNewProduct"/>
    	   	<property name="commandClass" value="springapp.domain.Product" />
    	  	<property name="validator">
    	   		<bean class="springapp.service.NewProductValidator"/>
    	   	</property>
    	   	<property name="formView" value="addproducts"/>
    	   	<property name="successView" value="hello.htm"/>
    	   	<property name="productManager" ref="productManager"/>
       </bean>
       
        <!-- changes for Annotations: Position of this block did not matter -->
    	<context:component-scan base-package="springapp.web" />
    	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
        
      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
           <property name="prefix" value="/WEB-INF/jsp/"></property>
           <property name="suffix" value=".jsp"></property>        
       </bean>
    	
    </beans>
    Apart from this nothing was changed.
    Configuration: Spring MVC 2.5 + HSQL + Apache Tomcat 6.0.26

    Please let me know your thoughts...
    Thanks,
    Vikram

  9. #9
    Join Date
    Aug 2010
    Posts
    3

    Default

    oops I forgot to mention the error I was receiving when I tried to hit "hello.htm"
    org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping for [/springapp/hello.htm] in DispatcherServlet with name 'springapp'

    However, as you can see in my dispatcher servlet (previous post) that "hello.htm" was defined as:
    Code:
    <bean name="/hello.htm" class="springapp.web.InventoryController">
      	<property name="productManager" ref="productManager" />
      </bean>
    Thanks,
    Vikram

  10. #10
    Join Date
    Jul 2010
    Location
    Venice, Italy
    Posts
    709

    Default

    Add the following bean definition in your springapp-servlet.xml:

    Code:
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    The SimpleControllerHandlerAdapter is used as default by Spring web mvc when no adapter is explicitly defined. But when you activate annotated controllers, by explicitly defining the AnnotationMethodHandlerAdapter, you override the default, so you have to explicitly define both adapters if you want both approaches to exist in the same application.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •