Я новичок в Spring и создаю весеннее веб-приложение. В приложении, которое я пишу, есть Class PreLoadService. В этом классе есть метод, определенный с помощью @PostConstruct, который вызывает DAO для загрузки данных. Экземпляр DAO объявлен в классе с @autowired.

Затем Контроллер для JSP объявляет экземпляр PreLoadService и вызывает геттер для извлечения данных, которые должны были быть загружены в @PostConstruct. Данные никогда не загружаются, и на @autowired также создается исключение.

Поскольку это не сработало, я попробовал простую версию Hello World, чтобы написать сообщение, и получил ту же проблему. Я отправлю это. В папке WEB_INF у меня есть web.xml и spring3-servlet.xml. В папке SRC у меня есть applicationContext.xml. Я работаю на Tomcat 7.

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>root.webpath</param-value>
</context-param>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>spring3</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring3</servlet-name>
    <url-pattern>*.html</url-pattern>
     <url-pattern>/</url-pattern>
</servlet-mapping></web-app>

spring3-servlet.xml

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <!--will allow Spring to load all the components from package and all its child packages-->    
<mvc:annotation-driven />
<context:component-scan
    base-package="com.nikki.spring3.controller" />
<!-- will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jsp to the view in ModelAndView.  -->       
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
</beans>

applicationContext.xml

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <mvc:annotation-driven/>   
 <context:component-scan base-package="com.nikki.spring3">
 <context:exclude-filter    expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan> 
<bean id="helloWorldService" 
    class="com.nikki.spring3.beansit.HelloWorldService">
    <property name="message" value="Preloading Init Config and Data" />

HelloWorldService

public class HelloWorldService {

 private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public String getMessage(){
      System.out.println("Your Message : " + message);
      return message;
   }
   @PostConstruct
   public void init(){
      System.out.println("Bean is going through init.");
   }
   @PreDestroy
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}

HelloWorldController

 @Controller
public class HelloWorldController {
    @Autowired 
    HelloWorldService helloWorldService;
/* RequestMapping annotation tells Spring that this Controller should
 *  process all requests beginning with /hello in the URL path. 
 *  That includes /hello/* and /hello.html.
 */
    @RequestMapping("/hello")
    public ModelAndView helloWorld() {

        String message =helloWorldService.getMessage();
                //"Hello World, Spring 3.0!";
        return new ModelAndView("hello", "message", message);
    }
}

Сообщение об ошибке

Exception
SEVERE: StandardWrapper.Throwable  org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': 
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'helloWorldController': 
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: com.nikki.spring3.beansit.HelloWorldService com.nikki.spring3.controller.HelloWorldController.helloWorldService; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [com.nikki.spring3.beansit.HelloWorldService] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)

Я ценю любую помощь. Благодарю.

0
T.Nee 27 Апр 2016 в 19:09

3 ответа

Лучший ответ

Если у вас есть файлы конфигурации, отличные от xxx-servlet.xml, вам необходимо сообщить Spring, что эти файлы существуют. Для этого вы должны использовать contextConfigLocation вместе с ContextLoadListener. Попробуйте добавить следующие строки в свой web.xml. Если applicationContext.xml существует в папке WEB-INF проекта, используйте следующее.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>

Я думаю, у вас был ваш applicationContext.xml в папке src. В этом случае используйте, как показано ниже

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
</context-param> 
1
Aditya 28 Апр 2016 в 04:09

В вашем случае вы хотите ввести bean-компонент, который еще не создан

Добавить @Service

Открытый класс @Service HelloWorldService {......}

0
Med 27 Апр 2016 в 16:59

Попробуйте создать интерфейс для HelloWorldService и автоматически подключитесь к этому интерфейсу в вашем контроллере. Spring создает компонент прокси класса HelloWorldService, поэтому сам HelloWorldService может быть недоступен для автоматического подключения. Попытайся.

0
TheKojuEffect 27 Апр 2016 в 16:55