springmvc在非controller里使用@Autowired失败


如题,这是自定义标签 这里获取不到biz


 public class FormatTimeTaglib extends BodyTagSupport {

    @Autowired
    private UserBiz uBiz;

    // serialVersionUID:{描述属性}
    private static final long serialVersionUID = -5465406084026930958L;

    private String time;

    @Override
    public int doStartTag() throws JspException {
        if(NullUtils.stringIsNull(time)){
            return SKIP_BODY;
        }else{
            System.out.println("############uBiz : "+(uBiz==null));

            return EVAL_BODY_INCLUDE;
        }
    }

UserBiz


 public interface UserBiz extends GenericDao<User>{

    public boolean user_exists(final String email,final String pwd);

}

UserBizImpl


 @Service
@Transactional
public class UserBizImpl extends GenericDaoImpl<User> implements UserBiz {

    @Resource UserTimelineBiz utlBiz;
    @Resource UserMedalBiz umBiz;
    @Resource MedalBiz medalBiz;

    @Override
    public boolean user_exists(String email, String pwd) {
        ...
    }
}

GenericDao


 public interface GenericDao<T> {
    private void save();
}

GenericDaoImpl


 @Transactional
public abstract class GenericDaoImpl<T> implements GenericDao<T>{
    protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());
    @PersistenceContext protected EntityManager em;

    public void save(){
        ...
    }
|

beans.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.kk" />
    <!-- 必须要加 -->
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
    <mvc:resources location="/resources/" mapping="/resources/**" />

    <context:annotation-config />

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 驱动名称 -->
        <property name="DriverClassName" value="com.mysql.jdbc.Driver" />

        <!-- 基本属性 url、user、password -->
        <property name="url"
            value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
            value="20" />

        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
        <property name="filters" value="stat" />
    </bean>

    <!-- JPA实体工厂配置 -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 扫描实体路径 -->
        <property name="packagesToScan" value="com.kk.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <!--设置外连接抓取树的最大深度 -->
                <prop key="hibernate.max_fetch_depth">3</prop>
                <prop key="hibernate.jdbc.fetch_size">18</prop>
                <prop key="hibernate.jdbc.batch_size">10</prop>
                <!-- 自动建表类型 validate|create|create-drop|update -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 是否显示SQL -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 显示SQL是否格式化 -->
                <prop key="hibernate.format_sql">false</prop>
                <!-- 关闭二级缓存 -->
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>

            </props>
        </property>
    </bean>

    <!-- 配置 jdbcTemplate -->
    <bean id="jdbcTemplate"
        class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

    <!-- 事务 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
        lazy-init="true">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

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

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀,在requestmapping输入的地址后自动调用该类进行视图解析 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- annotation默认的方法映射适配器 -->
    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean id="handlerAdapter"
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

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


</beans>

web.xml


 <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>question</display-name>

    <!-- logback  
    <context-param>  
        <param-name>logbackConfigLocation</param-name>  
        <param-value>classpath:logback.xml</param-value>  
    </context-param> --> 

    <!-- encoding -->
    <filter>  
        <filter-name>CharacterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CharacterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 


    <!-- <listener>
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>  
    </listener>  
   -->
    <!-- Spring view分发器 --> 
    <servlet>  
        <servlet-name>dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:beans.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>dispatcher</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>

</web-app>

求高手帮忙啊

spring-mvc spring controller

sun11 10 years, 3 months ago

 <context:component-scan base-package="com.kk" />

这个代表只扫这个目录下的 Bean ,加上你其它的包就好了,例如:


 <context:component-scan base-package="com.kk" />
<context:component-scan base-package="com.kk.service" />

ares38 answered 10 years, 3 months ago

上面说的不对吧


 <context:component-scan base-package="com.kk" />

  1. 这个 use-default-filters 默认是true,会扫描该包和子包的所有类的
  2. 建议你用 @Resource ,不要用 Autowired
  3. 你在spring配置文件中,已经用了 <context:component-scan /> 这个标签了,也就是隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor CommonAnnotationBeanPostProcessor 这两个bean了,所以就不再需要 <context:annotation-config /> 了,引用下spring的原文:

      
       The use of <context:component-scan> implicitly enables the   
    functionality of <context:annotation-config>. There is usually no 
    need to include the <context:annotation-config> element when using    
    <context:component-scan>.
      
     
  4. 用@Service的时候,最好标明名称,如 @Service("userBiz")

说的有不对的,指出来哈,虽然没解决你问题

kuanyin answered 10 years, 3 months ago

Your Answer