@PostConstuct 似乎不起作用并且@autowire 给出错误

@PostConstuct does not appear to work and @autowire gives an error

我是 spring 的新手,正在创建一个 spring 网络应用程序。 我正在编写的应用程序有一个 Class PreLoadService。在这个 class 中是一个用 @PostConstruct 定义的方法,它调用 DAO 来加载数据。 DAO 实例在 class 中用 @autowired.

声明

JSP 的控制器然后声明 PreLoadService 的一个实例并调用 getter 来检索本应加载到 @PostConstruct 中的数据。永远不会加载数据,并且还会在 @autowired.

上引发异常

由于这不起作用,我尝试了一个简单的 Hello World 版本来编写消息并收到了同样的问题。我会post这个。在 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)

感谢任何帮助。谢谢。

尝试为 HelloWorldService 创建一个接口,并在您的控制器中使用该接口自动装配。 Spring 创建 class HelloWorldService 的代理 bean,因此 HelloWorldService 本身可能无法自动装配。尝试一下。

在您的情况下,您想要注入一个尚未创建的 bean

添加@Service

@服务 public class HelloWorldService { ...... }

如果您有 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>