2013-12-20 2 views
0

Я пытаюсь внедрить свойство со значением внутри моего контроллера, используя конфигурационный файл Spring Framework servlet.xml. Мой контроллер начинает как этотInject Spring определяет свойство в контроллере

package lv.lu.meetings.portal.mvc.controller; 

import java.util.ArrayList; 
import java.util.List; 

import javax.servlet.http.HttpSession; 

import lv.lu.meetings.domain.jpa.User; 
import lv.lu.meetings.domain.jpa.meeting.Attendance; 
import lv.lu.meetings.domain.jpa.meeting.Invite; 
import lv.lu.meetings.domain.jpa.meeting.InviteStatus; 
import lv.lu.meetings.domain.jpa.meeting.Meeting; 
import lv.lu.meetings.domain.jpa.notification.Notification; 
import lv.lu.meetings.domain.redis.Friend; 
import lv.lu.meetings.interfaces.service.NotificationService; 
import lv.lu.meetings.interfaces.service.UserService; 
import lv.lu.meetings.portal.mvc.WebConst; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Component; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 

/** 
* Controller for displaying application home page. 
* 
* Supports multiple tab views: Main, Friends, Notifications, Meetings. 
*/ 


@Controller 
public class HomePageController { 

    // limit meeting count 
    // defined in meetings-servlet.xml 
    private String limit; 
    public String getLimit() { 
     return limit; 
    } 

    public void setLimit(String limit) { 
     this.limit = limit; 
    } 

Мой файл встречи-servlet.xml подобно этому

<?xml version="1.0" encoding="UTF-8"?> 

<!-- Spring Web application configuration file --> 

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 

    <!-- Support for component autowiring --> 
    <context:component-scan base-package="lv.lu.meetings"/> 

    <!-- URL mapping for annotation-based Spring Web MVC controllers --> 
    <bean id="urlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> 
     <property name="interceptors"> 
      <list> 
       <ref bean="loginInterceptor"/> 
      </list> 
     </property> 
    </bean> 

    <!-- Limit output data --> 
    <bean id="HomePageController" class="lv.lu.meetings.portal.mvc.controller.HomePageController"> 
     <property name="limit" value="10" /> 
    </bean> 

я получаю ошибку

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'urlMapping' defined in ServletContext resource [/WEB-INF/meetings-servlet.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot map handler 'HomePageController' to URL path [/home]: There is already handler of type [class lv.lu.meetings.portal.mvc.controller.HomePageController] mapped. 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529) 

Это определенно SMTH легко настроить, но я Я новичок в Java и Spring Framework, поэтому помощь приветствуется. Благодаря!

ответ

0

Вы в настоящее время создаете 2 HomePageController beans. Один из

<!-- Limit output data --> 
<bean id="HomePageController" class="lv.lu.meetings.portal.mvc.controller.HomePageController"> 
    <property name="limit" value="10" /> 
</bean> 

, а другой из

<context:component-scan base-package="lv.lu.meetings"/> 

и @Controller аннотацию на

@Controller 
public class HomePageController { 

Предполагая, что у вас есть метод @RequestMapping обработчика в этом классе, Spring будет пытаться зарегистрировать его в два раза и сбой, поскольку у вас не может быть двух обработчиков для одного и того же URL-адреса.

Выберите один или другой компонент. Если вы хотите идти аннотации пути, вы можете придать значению непосредственно

@Value("10") 
private String limit; 

или использовать property placeholder.

+0

права , у меня также есть \t @RequestMapping (value = "/ home/meeting", method = RequestMethod.GET) public String displayMeetings (ModelMap model, HttpSession session) {mapping, где я хочу использовать свое определенное свойство. Как я могу выбрать только один? Я не могу удалить Slammer

+0

@Slammer Затем избавиться от '' декларации для 'HomePageController' и найти другой способ установить ограничение. Один из них - то, как я описал. –

+0

Да, но с предоставленным синтаксисом примера заполнителя свойства кажется, что он действителен только для jstl – Slammer

0

Вы можете установить свойство с @Value аннотацию чтения значения из файла свойств (или любой другой):

@Value("${my.limit}") 
private String limit; 

Вы также можете исключить HomePageController из сканирования компонента:

<context:component-scan base-package="lv.lu.meetings"> 
    <context:exclude-filter type="regex" expression="HomePageController$"/> 
</context:component-scan> 
Смежные вопросы