代码改变世界

对SpringMVC注解注入的理解

2014-02-24 14:31  西风狂诗曲  阅读(657)  评论(0编辑  收藏  举报

最近由于项目要求,要求用SpringMVC进行项目的开发,所以就到网上找资料,进行SpringMVC的练习,为了以后的项目做准备。首先我们先来看一下SpringMVC的配置吧。

项目截图

 

(1)web.xml的配置

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<!-- application的加载路径 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- SpringMVC处理的核心 -->
<servlet>
<servlet-name>yygl</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 找到servlet,注意必然还有一个yygl-servlet.xml与之对应 -->
<servlet-mapping>
<servlet-name>yygl</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

 

(2)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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
    default-autowire="byName">

    <!-- setup spring annotation scan -->
    <context:component-scan base-package=".">
    </context:component-scan>
    <!-- dataSource -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/ylgl" />
        <property name="username" value="root" />
        <property name="password" value="xuzhang" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />

         <!-- 开启Druid的监控统计功能 -->
         <property name="filters" value="stat" /> 
        <!--<property name="filters" value="mergeStat" />
    --></bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
            </props>
        </property>
        <property name="mappingDirectoryLocations">
            <list><!-- 实体 -->
            <value>classpath:com/xuzhang/cn/entity/</value>
            </list>
        </property>
        </bean>
        <!-- HibernateTemplate bean-->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- Configuration Affairs -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Cut point cut all service -->
     
    <aop:config>
        <aop:advisor pointcut="execution(* org.commonframe.hibernate..*Service*.*(..) )"
            advice-ref="txAdvice" />
        <aop:advisor pointcut="execution(* com.xuzhang.cn.jcxx..*Service*.*(..) )"
            advice-ref="txAdvice" />
    </aop:config>

    <!--
        All at the beginning of the find, query, search method does not apply
        transactions
    -->
    
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="find*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="search*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="check*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="load*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="createTask" propagation="NEVER" />
            <tx:method name="create*" />
            <tx:method name="save*" />
            <tx:method name="update*" />
            <tx:method name="delete*" />
            <tx:method name="remove*" />
            <tx:method name="batch*" />
            <tx:method name="execute*" />
            <tx:method name="upload*" />
            <tx:method name="add*" />
            <tx:method name="del*" />
        </tx:attributes>
    </tx:advice> 
        </beans>

 

(3)yygl-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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
    default-autowire="byName">
       
     <context:annotation-config />   
       <!-- 把标记了@Controller注解的类转换为bean -->     
      <context:component-scan base-package="com.xuzhang.cn.controller" />     
    <!-- ViewResolver --> 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"     
          p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />        
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <!-- 处理器 -->
</beans>  

 (4)Controller

package com.xuzhang.cn.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.commonframe.hibernate.util.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.xuzhang.cn.entity.User;
import com.xuzhang.cn.services.UserService;

@Controller
@RequestMapping("/login.do")
public class Login {
    private UserService userService;
    
    public Login() {
        super();
    }
    
    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    protected CommonService<User> getCommonService(){
        return (CommonService<User>)this.userService;
    }
    @RequestMapping(params = "method=add")
    public String add(HttpServletRequest request,HttpServletResponse response){
        
        String id = "";
        List<User> data = this.getCommonService().findListByHQL("from User", null);
        if("".equals(id)){
            
        }
         return "student_add";
    }
}

(5)service层

  service

  

package com.xuzhang.cn.services;

import org.commonframe.hibernate.util.CommonService;

import com.xuzhang.cn.entity.User;
public interface UserService extends CommonService<User>{

}

  serviceImpl

 

package com.xuzhang.cn.services.impl;

import org.commonframe.hibernate.util.CommonServiceImpl;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.xuzhang.cn.dao.UserDao;
import com.xuzhang.cn.entity.User;
import com.xuzhang.cn.services.UserService;
@Scope("singleton")
@Service("userService")
public class UserServiceImpl  extends CommonServiceImpl<User> implements UserService{
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    
}

(6)dao层

  userDao

package com.xuzhang.cn.dao;

import org.commonframe.hibernate.util.CommonHibernateDao;

import com.xuzhang.cn.entity.User;

public interface UserDao extends CommonHibernateDao<User>{
}

  userDaoImpl

package com.xuzhang.cn.daoimpl;

import org.commonframe.hibernate.util.CommonHibernateDaoImpl;
import org.springframework.stereotype.Component;

import com.xuzhang.cn.dao.UserDao;
import com.xuzhang.cn.entity.User;
@Component("userDao")
public class UserDaoImpl extends CommonHibernateDaoImpl<User> implements UserDao{
}

  由于原来用的是SSH框架,刚开始用SpringMVC的时候,Service死活都注入不进来,最后在网上查找了大量的资料,最后通过一个人的回答解决了我的困惑,具体那个人我忘记了,- -!!,原来的struts2的action通过了插件struts2-spring-plugin-2.2.1.jar来将struts2的action被Spring进行管理。而我刚开始的时候用的是直接实现了spring的Controller接口,所以导致了该action无法注入service,按照我的理解就是没有被spring进行管理。

[org.springframework.beans.factory.support.DefaultListableBeanFactory]Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1644028: defining beans [login,userDao,userService,commonHibernateDao,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,dataSource,sessio]

这是我们控制台所打印的数据,里面看到了已经扫描的beans里面已经包含了login(@Controller Spring所扫描到的)。