如果bean是自动装配的,如何创建新的spring bean?

时间:2014-02-04 12:38:14

标签: java spring

In this code i already have a bean autowired in the xml, but i need to create a new bean again and it gives me error
SEVERE:

    ERROR 2014-02-04 17:52:29,934 [http-8080-5] (FrameworkServlet.java:314) (initServletBean) - Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hmkcode.spring.mvc.model.FileMeta com.hmkcode.spring.mvc.controllers.FileController.fileMeta; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileMeta': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hmkcode.spring.mvc.model.FileMeta com.hmkcode.spring.mvc.model.FileMeta.fileMeta; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.hmkcode.spring.mvc.model.FileMeta] 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.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1064)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:574)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
        at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
        at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
        at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
        at javax.servlet.GenericServlet.init(GenericServlet.java:212)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1213)
        at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Thread.java:701)

Code:

这是我的spring xml文件,我需要在这里获取我在控制器中创建的bean的evey实例的fileSystemPath属性表单。 。 。 。 .................................................. .................................................. ...........................

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

    <context:component-scan base-package="com.hmkcode.spring.mvc" />
    <mvc:annotation-driven />

    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    <context:annotation-config />
    <bean id="fileMeta" scope="prototype" class="com.hmkcode.spring.mvc.model.FileMeta">
        <property name="fileSystemPath" value="/home/mohan/extra/data/cmsPhoto/"/>
    </bean>
</beans>







Hi this is my bean file and all i am trying to do is get value from xml and create multiple instances of the bean................................................

    @JsonIgnoreProperties({"bytes"})
    @Component
    public class FileMeta
    {
        private String fileName;
        private String fileSize;
        private String fileType;
        private String fileSystemPath;

        private byte[] bytes;

        public String getFileName() {
            return fileName;
        }
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
        public String getFileSize() {
            return fileSize;
        }
        public void setFileSize(String fileSize) {
            this.fileSize = fileSize;
        }
        public String getFileType() {
            return fileType;
        }
        public void setFileType(String fileType) {
            this.fileType = fileType;
        }
        public String getFileSystemPath()
        {
            return fileSystemPath;
        }
        public void setFileSystemPath(String fileSystemPath)
        {
            this.fileSystemPath = fileSystemPath;
        }
        public byte[] getBytes() {
            return bytes;
        }
        public void setBytes(byte[] bytes) {
            this.bytes = bytes;
        }
        @Override
        public String toString()
        {
            return "FileMeta [fileName=" + fileName + ", fileSize=" + fileSize
                + ", fileType=" + fileType + ", fileSystemPath="
                + fileSystemPath + "]";
        }
        @Override
        public boolean equals(Object obj)
        {
            if (getClass() != obj.getClass())
            {
            return false;
            }
            FileMeta other = (FileMeta) obj;
            if((fileName.equals(other.fileName)) && (fileSize.equals(other.fileSize)) && (fileType.equals(other.fileType)))
            {
            return true;
            }
            else
            return false;
        }
    }

    package com.hmkcode.spring.mvc.controllers;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;

    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.collections.list.SetUniqueList;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;

    import com.hmkcode.spring.mvc.model.FileMeta;

    @Controller
    @RequestMapping("/controller")
    public class FileController {
        @Autowired
        FileMeta fileMeta;
    //  String fileSystemPath = fileMeta.getFileSystemPath();
        /***************************************************
         * URL: /rest/controller/upload  
         * upload(): receives files
         * @param request : MultipartHttpServletRequest auto passed
         * @param response : HttpServletResponse auto passed
         * @return LinkedList<FileMeta> as json format
         ****************************************************/
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
        int i = 0;
        @RequestMapping(value="/upload", method = RequestMethod.POST)
        public synchronized @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response)
        {
            System.out.println("#################### Hit Upload");
             Iterator<String> itr =  request.getFileNames();

             while(itr.hasNext())
             {
             FileMeta fileMeta = new FileMeta();
    //       fileMeta.setFileSystemPath(fileSystemPath);

             MultipartFile mpf = null;
                 mpf = request.getFile(itr.next()); 
                 if(files.size() >= 10)
                     files.pop();
                 fileMeta.setFileName(mpf.getOriginalFilename());
                 fileMeta.setFileSize(mpf.getSize() / 1024+" Kb");
                 fileMeta.setFileType(mpf.getContentType());
                 System.out.println("%%% List(A): "+files);
                 if(files.contains(fileMeta))
                 {
                     System.out.println(fileMeta+" -- Already Present");
                     continue;
                 }
                 else
                 {
                     try {
                     fileMeta.setBytes(mpf.getBytes());

                     FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(fileMeta.getFileSystemPath()+""+fileMeta.getFileName()));
    //              FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream("/home/mohan/extra/data/cmsPhoto/"+mpf.getOriginalFilename()));
                     System.out.println("===========> "+fileMeta.getFileName()+" : (OG): "+mpf.getOriginalFilename() +" Uploaded! "+mpf.getSize()/1024+" Kb");
                     }catch (IOException e){}
                     files.add(fileMeta);
                 }

    //           FileMeta file = new FileMeta();
    //           file.setFileName(mpf.getOriginalFilename());
    //           file.setFileSize(""+mpf.getSize()/1024+" Kb");
    //           file.setFileType(mpf.getContentType());
                 //2.4 add to files
    //       itr.remove();
    //       files.remove(fileMeta);
                 System.out.println("%%% List(B): "+files);
             }//end while

             // result will be like this
             // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
             return files;
        }
    }

1 个答案:

答案 0 :(得分:2)

我通过实现ApplicationContextAware并创建新的spring bean来解决它:

public FileMeta getFileMeta()
{
 return applicationContext.getBean("fileMeta", FileMeta.class); 
}

和spring xml看起来像这样:

<context:component-scan base-package="com.hmkcode.spring.mvc" />
<mvc:annotation-driven />

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<context:annotation-config />
<bean id="fileMeta" scope="prototype" class="com.hmkcode.spring.mvc.model.FileMeta">
    <property name="fileSystemPath" value="/home/mohan/extra/data/cmsPhoto/"/>
</bean>