首页 > Controller 中 Autowried Service 层可以用 DAO 启动就报错

Controller 中 Autowried Service 层可以用 DAO 启动就报错

Controller 中 Autowried Service 层可以用 DAO 启动就报错

请输入代码
package com.ysotek.qxy.mermaid.open.customer.api.action.society;

import com.vt1314.framework.extend.action.BaseAction;
import com.vt1314.framework.sugar.data.QueryParam;
import com.vt1314.framework.sugar.func.file.FileUtils;
import com.ysotek.qxy.mermaid.common.config.ConstantKeyFilePath;
import com.ysotek.qxy.mermaid.modules.jpush.JPush;
import com.ysotek.qxy.mermaid.modules.profile.biz.UserBiz;
import com.ysotek.qxy.mermaid.modules.profile.entity.User;
import com.ysotek.qxy.mermaid.modules.society.biz.SocietyFriendBiz;
import com.ysotek.qxy.mermaid.modules.society.biz.SocietyLikeBiz;
import com.ysotek.qxy.mermaid.modules.society.biz.SocietyPublishBiz;
import com.ysotek.qxy.mermaid.modules.society.biz.SocietyResponseBiz;
import com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao;
import com.ysotek.qxy.mermaid.modules.society.entity.SocietyFriend;
import com.ysotek.qxy.mermaid.modules.society.entity.SocietyLike;
import com.ysotek.qxy.mermaid.modules.society.entity.SocietyPublish;
import com.ysotek.qxy.mermaid.modules.society.entity.SocietyResponse;
import com.ysotek.qxy.mermaid.modules.tools.ImgTranslation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 社交模块
 * Created by lenovo on 2016/4/8.
 */
@Controller
@RequestMapping("/api/security/society")
public class SocietyAction extends BaseAction {
    @Autowired
    private SocietyResponseBiz societyResponseBiz;
    @Autowired
    private SocietyLikeBiz societyLikeBiz;
    @Autowired
    private SocietyFriendBiz societyFriendBiz;
    @Autowired
    private UserBiz userBiz;
    @Autowired
    private SocietyPublishBiz societyPublishBiz;

    @Autowired
    private  SocietyPublishDao societyPublishDao;

    private final static Logger logger = LoggerFactory.getLogger(SocietyAction.class);
    /*
    * 好友详情
    * @param userId 好友id
    * */
    @RequestMapping("/friendDetail")
    @ResponseBody
    public JSONObject getFriendDetail(@RequestParam(name = "userId",required = false)String userId){

        JSONObject result=new JSONObject();
        result.put("userId","用户id");
        result.put("userName","用户名");
        result.put("image","用户头像");
        result.put("sex","姓别");
        result.put("sign","个性签名");
        return  result;
    }

    /*
    * 圈子信息列表接口
    * @param userId 用户Id
    * @param type 显示(1、all 2、friend 3、myself)
    * @param pageNowParam  当前页数
    * @param pageSizeParam 每页记录数
    * */
    @RequestMapping("/communityList")
    @ResponseBody
    public JSONObject getCommunityList(@RequestParam(name = "userId",required = false)String userId,
                                       @RequestParam(name = "pageNowParam",required = false)String pageNowParam,
                                       @RequestParam(name = "pageSizeParam",required = false)String pageSizeParam,
                                       @RequestParam(name = "type",required = false)String type
    ){

        JSONObject result=new JSONObject();
        JSONArray list=new JSONArray();
        int s=pageNowParam==null?0:Integer.parseInt(pageNowParam);
        int n=pageSizeParam==null?3:Integer.parseInt(pageSizeParam);
        for(int i=s;i<n;i++){
            JSONObject item=new JSONObject();
            item.put("userNme","用户名"+i);
            item.put("publishContent","发布内容");
            item.put("images","图片");
            item.put("starNum","点赞数");
            list.add(item);
        }
        result.put("list",list);
        return  result;
    }

    /*
    评论朋友圈
     */
    @RequestMapping("/response")
    @ResponseBody
    public String addResponse(SocietyResponse societyResponse){
        societyResponseBiz.addOrUpdate(societyResponse);
        return "1";
    }
    /*
    点赞
     */
    @RequestMapping("/like")
    @ResponseBody
    public String addlike(SocietyLike societyLike){
        societyLikeBiz.addOrUpdate(societyLike);
        return "1";
    }
    /**
     *添加好友接口
     * @param userId 用户id
     * @param friendId 好友id
     **/
    @RequestMapping("/addFriend")
    @ResponseBody
    public JSONObject addFriend(@RequestParam(name = "userId",required = false)String userId,
                                @RequestParam(name = "friendId",required = false)String friendId
    ){
        User user=new User();
        User friend=new User();
        JSONObject result=new JSONObject();
        if(!(StringUtils.isEmpty(userId)&&StringUtils.isEmpty(friendId)))
        {
            user=userBiz.findModel(Long.parseLong(userId));
            friend=userBiz.findModel(Long.parseLong(friendId));
            if(user!=null&&friend!=null)
            {
                if(!societyFriendBiz.isFriends(user,friend)) {
                    SocietyFriend societyFriend = new SocietyFriend();
                    societyFriend.setUser(user);
                    societyFriend.setFriend(friend);
                    societyFriend.setCreateTime(new Date());
                    societyFriendBiz.addOrUpdate(societyFriend);
                    //jpush推送
                    JPush jPush=new JPush();
                    jPush.pushMessage(user.getName()+"想要添加你为好友","好友添加",friend.getAlias());
                    result.put("isOk", "addOk");
                }
                else
                {
                    result.put("err","已经是此用户好友不可重复添加");
                }
            }
            else
            {
                result.put("err","用户或好友不存在");
            }
        }
        else
        {
            result.put("err","必要参数为空");
        }
        return  result;
    }
    /**
     *好友列表接口
     * @param userId 用户id
     **/
    @RequestMapping("/friendList")
    @ResponseBody
    public JSONObject friendList(@RequestParam(name = "userId",required = false)String userId,HttpServletRequest request
    ){

        User user=new User();
        JSONObject result=new JSONObject();
        if(!StringUtils.isEmpty(userId))
        {
            user=userBiz.findModel(Long.parseLong(userId));
            if(user!=null)
            {
                return societyFriendBiz.getMyFriendList(user,request);
            }
            else
            {
                result.put("err","用户不存在");
            }
        }
        else
        {
            result.put("err","必要参数为空");
        }
        return  result;
    }
    /**
     * 发布圈子信息接口
     * @param userId 用户Id
     * @param authority 可见性权限 (1、全部可见2、朋友可见3、男可见4、女可见)
     * @param content 发布内容
     * @param publishTime 发布时间
     * @param images 附带图片
     * @param notifyUser 提醒用户可见(userId用逗号分开)
     **/
    @RequestMapping("/postCommunity")
    @ResponseBody
    public JSONObject postCommunity(@RequestParam(name = "userId",required = false)String userId,
                                    @RequestParam(name = "authority",required = false)String authority,
                                    @RequestParam(name = "content",required = false)String content,
                                    @RequestParam(name = "publishTime",required = false)String publishTime,
                                    @RequestParam(name = "images",required = false)MultipartFile[] images,
                                    @RequestParam(name = "notifyUser",required = false)String notifyUser,
                                    HttpServletRequest request

    ){
        JSONObject result=new JSONObject();
        //验证必要数据是否为空
        if(!(StringUtils.isEmpty(userId)||StringUtils.isEmpty(content)||StringUtils.isEmpty(publishTime)))
        {
            if(images.length>3)
            {
                result.put("err","图片数量多于三张");
                return  result;
            }
            String path = null;
            String path1="";
            for(MultipartFile image:images) {
                if (image != null && !image.isEmpty()) {
                    path = FileUtils.fileUpload(image, ConstantKeyFilePath.SOCIETY_DIR,
                            "society", request);
                }
                path1 += "/" + path+";";
            }
            /*String []p=path1.split(";");
            for(String p1:p)
            {
                System.out.println(p1);
            }*/
            SocietyPublish societyPublish=new SocietyPublish();
            if(userBiz.findModel(Long.parseLong(userId))!=null) {
                societyPublish.setUser(userBiz.findModel(Long.parseLong(userId)));
                societyPublish.setContent(content);
                societyPublish.setPicAddress(path1);
                if(StringUtils.isEmpty(authority))
                {
                    societyPublish.setWhoCanSee('0');
                }
                else {
                    societyPublish.setWhoCanSee(authority.charAt(0));
                }
                societyPublish.setAttentionUserId(notifyUser);
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date date = sdf.parse(publishTime);
                    societyPublish.setPublishTime(date);
                    societyPublishBiz.addOrUpdate(societyPublish);
                    result.put("isOk","postCommunity ok");
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                result.put("err", "用户不存在");
            }
        }

        return  result;
    }
    /**
     * 娱乐圈 全部 (含男女可见判断)
     * @param sex 性别 不输入就查询出对所有人可见的信息
     * */
    @RequestMapping("/getAllCommunity")
    @ResponseBody
    public JSONObject getAllCommunity(@RequestParam(name = "sex",required = false)String sex,HttpServletRequest request
    )
    {
        String []picAddress=new String[1];
        picAddress[0]="picAddress";
        JSONObject result=new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("allCanSee", "1");
        //性别输入为空 查询出对所有人可见的朋友圈信息
        if(StringUtils.isEmpty(sex)) {
            return ImgTranslation.imgtras(societyPublishBiz.findJSONList(queryParam),picAddress,request);
        }
        //有输入判断输入是什么 再根据输入情况执行不同查询
        else{
            if("男".equals(sex))
            {
                queryParam.getSqlMap().put("maleCanSee", "3");
            }else if("女".equals(sex))
            {
                queryParam.getSqlMap().put("feMaleCanSee", "4");
            }
            else
            {
                result.put("err","性别输入有误");
            }
            if(result.has("err"))
            {
                return result;
            }
            else {

                return ImgTranslation.imgtras(societyPublishBiz.findJSONList(queryParam), picAddress, request);
            }
        }
    }
    /**
     * 娱乐圈 好友(默认加载出对所有好友可见的朋友圈)
     * @param userId
     * */
    @RequestMapping("/getMyFriendsCommunity")
    @ResponseBody
    public JSONObject getMyFriendsCommunity(@RequestParam(name = "userId",required = false)String userId,HttpServletRequest request
    )
    {
        JSONObject result=new JSONObject();
        User user=userBiz.findModel(Long.parseLong(userId));
        if(user!=null) {
            //找出好友列表
            JSONObject friendJson=societyFriendBiz.getMyFriendList(user,request);
            Set list=friendJson.entrySet();
            List friendList=new ArrayList<String>();
            Iterator iterator=list.iterator();
            while(iterator.hasNext())
            {
                String json=iterator.next().toString();
                String userJson=json.substring(json.indexOf('{'),json.length());
                //得到好友id
                String userId1=userJson.substring(10,userJson.indexOf(','));
                friendList.add(userId1);
                logger.info(userId1);
            }
            //根据好友id到朋友圈表中查询符合条件的数据并返回
            if(friendList.size()==0)
            {
                result.put("isEmpty","empty");
            }else
            {
                return societyPublishBiz.findMyFriendsCommunity(friendList,request);
            }
        }
        else {
            result.put("err","用户不存在");
        }
        return  result;
    }
    /**
     * 娱乐圈 我的动态
     * @param userId
     * */
    @RequestMapping("/getMyCommunity")
    @ResponseBody
    public JSONObject getMyCommunity(@RequestParam(name = "userId",required = false)String userId,HttpServletRequest request
    ) {
        JSONObject result=new JSONObject();
        if(!StringUtils.isEmpty(userId))
        {
            QueryParam queryParam=new QueryParam();
            queryParam.getSqlMap().put("userId",userId);
            String []picAddress=new String[1];
            picAddress[0]="picAddress";
            return  ImgTranslation.imgtras(societyPublishBiz.findJSONList(queryParam),picAddress,request);
        }else
        {
            result.put("err","输入不能为空");
        }
        return  result;
    }
    /**
     * 圈子设置
     */
    @RequestMapping("/setwhocansee")
    @ResponseBody
    public String setPublish(@RequestParam(name = "userid",required = false)String userId,
                             @RequestParam(name = "num",required = false)String num){

          Integer a=societyPublishDao.setWhoCanSee(userId,num);
        if(a==1){
            return "设置成功!";
        }else {
            return "设置失败!";
        }
    }
}
refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'societyAction': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao com.ysotek.qxy.mermaid.open.customer.api.action.society.SocietyAction.societyPublishDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao] 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)}
2016-05-31 18:50:16  [org.springframework.web.servlet.DispatcherServlet]-[ERROR]  Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'societyAction': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao com.ysotek.qxy.mermaid.open.customer.api.action.society.SocietyAction.societyPublishDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao] 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:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    a
    
    配置文件
        <?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" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.ysotek.qxy">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

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

    <!--后台管理的包-->
    <!--后台管理的包-->
    <context:component-scan base-package="com.ysotek.qxy.mermaid.open"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/>

    <mvc:annotation-driven/>

    <!-- 上传接收100M的总文件大小 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="104857600"/>
    </bean>

    <!-- 当Spring容器启动完成后执行下面的这个Bean -->
    <bean class="com.ysotek.qxy.mermaid.common.start.InstantiationTracingBeanPostProcessor"/>

    <!--&lt;!&ndash;&lt;!&ndash; 拦截器 - 简单登录验证 &ndash;&gt;&ndash;&gt;-->
    <mvc:interceptors>
        <!--<mvc:interceptor>-->
            <!--<mvc:mapping path="/api/**"/>-->
            <!--<bean class="com.ysotek.qxy.mermaid.common.interceptor.VisitInfoInterceptor"/>-->
        <!--</mvc:interceptor>-->
        <!--<mvc:interceptor>-->
            <!--<mvc:mapping path="/api/security/**"/>-->
            <!--<bean class="com.ysotek.qxy.mermaid.common.interceptor.AuthorityInterceptor"/>-->
        <!--</mvc:interceptor>-->

        <!--酒吧管理后台操作拦截-->
        <mvc:interceptor>
            <mvc:mapping path="/BarManager/shop/**" />
            <mvc:exclude-mapping path="/BarManager/shop/login/**"/>
            <bean class="com.ysotek.qxy.mermaid.common.interceptor.BarManagerInterceptor" />
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/api/setting/**" />
            <mvc:mapping path="/api/security/society/**" />
            <mvc:exclude-mapping path="/api/auth/login/**"/>
            <bean class="com.ysotek.qxy.mermaid.common.interceptor.ApiInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

配置问题,把Dao的包加到base-package里就可以了。


看你的代码SocietyAction是在com.ysotek.qxy.mermaid.open.customer.api.action.society包下面,没错吧?

按照你的xml里的配置:

<!--后台管理的包-->
<context:component-scan base-package="com.ysotek.qxy.mermaid.open"/>

SocietyAction类应该是“后台管理”的一部分,对吧?

可你看你要注入的类com.ysotek.qxy.mermaid.modules.society.dao.SocietyPublishDao,压根不在扫描目录com.ysotek.qxy.mermaid.open下面啊,这要是能注入,那不见鬼了?


遇到这种问题:
1.查看注解是否已经添加
2.查看扫描component-scan是否包含未注入的文件

【热门文章】
【热门文章】