【问题标题】:@autowired annotation issue, not injecting bean in class, using Spring3.0, hibernate@autowired 注释问题,不在类中注入 bean,使用 Spring3.0,休眠
【发布时间】:2011-08-22 11:47:51
【问题描述】:

以下是我的课:

package com.abc.trade.util;

public class StockTraderLogger {

    static Logger logger = Logger.getLogger("StockTraderLogger");

    @Autowired
    ConfigService configService; 




    public static void debug(Object className, Object logMessage) {     
        try {
            System.out.println("in debug.. ");
            StockTraderLogger stl =new StockTraderLogger();
            stl.addMessage(""+convertToString(className)+"\t"+convertToString(logMessage));
            System.out.println("in debug..post ");
        } catch (DataAccessException e) {
            System.out.println("Caught exception...");
                e.printStackTrace();
        }
    }

    public void addMessage(String message) throws DataAccessException {
        System.out.println("in  add message of util. ");
        System.out.println("String: " + configService); 

        configService.addMessage(message);          
    }
}

@Autowire 注释不起作用。当调用addMessage 方法时,它会将configService 的值显示为null。但是它被正确地注入了我的一些控制器类中,但不是在这里。

谁能解释什么是问题?以及如何解决这个问题?

XML 的代码是:(beansdefinition.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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
           http://www.springframework.org/schema/aop


   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.abc.trade.util"/> 
      <context:component-scan base-package="com.abc.trade.service"/>

       <!-- Hibernate Configuration -->
       <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">    

                <property name="annotatedClasses">      
                    <list>
          <value>com.abc.trade.model.Order</value>  
          <value>com.abc.trade.model.Profile</value> 
          <value>com.abc.trade.model.Log</value>                
                    </list>    
                </property>  
           </bean>

            <tx:annotation-driven/> 

           <bean id="transactionManager" 
               class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                <property name="sessionFactory" ref="sessionFactory"/>
          </bean>

           <bean id="commonService" class="com.abc.trade.framework.service.CommonServiceImplementor">
                <property name="commonDao" ref="commonDao"/>
           </bean>

           <bean id="commonDao" class="com.abc.trade.framework.dao.HibernateDAO">
            <property name="sessionFactory"><ref local="sessionFactory"/></property>

           </bean>

            <bean id="configService" class="com.abc.trade.service.ConfigServiceImplementor" parent="commonService">
           </bean>

           <import resource="../context/springws-servlet.xml"/>
     </beans>

另一个XML是:(Springmvc-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:webflow="http://www.springframework.org/schema/webflow-config"
    xmlns:context="http://www.springframework.org/schema/context"
    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.xsd
        http://www.springframework.org/schema/webflow-config
        http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">

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


     <context:component-scan base-package="com.abc.trade.controller" />   
     <context:component-scan base-package="com.abc.trade.util"/>


     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages" />
    </bean>

     <!-- Exception Resolver -->
     <bean id="exceptionResolver"
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="com.abc.trade.framework.exception.DataAccessException">
                errorPage</prop>
                <prop key="java.sql.SQLException">errorPage</prop>
                <prop key="java.lang.Exception">errorPage</prop> 
            </props>
        </property>
    </bean>   

</beans>

提前谢谢你。

ConfigService:

package com.abc.trade.service;
import org.springframework.stereotype.Service;
import com.abc.trade.framework.exception.DataAccessException;

public interface ConfigService {

        public void addMessage(String message) throws DataAccessException;
}

配置服务实现者:

package com.abc.trade.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.abc.trade.framework.exception.DataAccessException;
import com.abc.trade.framework.service.CommonServiceImplementor;
import com.abc.trade.model.Log;
import com.abc.trade.model.Mode;
import com.abc.trade.util.StockTraderLogger;

@Service("configService")
public class ConfigServiceImplementor extends CommonServiceImplementor implements ConfigService{

    String errorMessage = "";

    @Override
    public void addMessage(String message) {
        System.out.println("in add message of service...........");
        Log log = new Log();
        try{
            log.setMessage(message);
            System.out.println("Message is: "+message);
            int i=save(log);
        }catch(Exception e)
        {
            errorMessage = "Error in saving debug message";
            e.printStackTrace();
            //throw new DataAccessException(errorMessage);
        }

    }

}

【问题讨论】:

  • ConfigService类的完整包类名是什么?我认为默认注入是按类型,而不是按名称。
  • 我在控制器中自动装配了这个 bean,它工作正常,但如果我在其他一些类中自动装配,那么它不会自动装配。
  • 你碰巧解决了sagar的问题吗????
  • @indyaah :不,目前我不在 Spring 上工作。

标签: hibernate spring spring-mvc annotations spring-annotations


【解决方案1】:

这里的问题在于调试方法:

    StockTraderLogger stl =new StockTraderLogger();

这不是弹簧管理的。您可以通过两种方式将 Spring 托管 bean 注入非托管 bean。 在这里,您可以将 configService 注入 StockTraderLogger 为:

1) 通过 AutowireCapableBeanFactory:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("beansdefinition.xml");
    StockTraderLogger stl = new StockTraderLogger();
    ctx.getAutowireCapableBeanFactory().autowireBeanProperties(stl, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);

2) 通过使用 Spring AOP @Configurable 注解将类标记为符合 Spring 驱动配置的条件(例如使用“new”运算符实例化的对象)。

    @Configurable
    public class StockTraderLogger {
    ...
    }

and specifying this <context:spring-configured/> in beansdefinition.xml. 

你可以找到更多关于这个spring aop方式here的信息。

【讨论】:

    【解决方案2】:

    将此添加到applicationContext.xml

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    http://www.springframework.org/schema/mvcxsi:schemalocation

    带注释的控制器和其他功能需要mvc-annotation驱动:

    &lt;mvc:annotation-driven /&gt;

    【讨论】:

    • 我也在我的应用程序中尝试过这个,不工作这是一个严重的问题。让我们尽可能关闭它。
    【解决方案3】:

    StockTraderLogger 未声明为 spring bean,并且在 spring 上下文中不存在,因此注入将不起作用。

    <bean id="StockTraderLogger" class="com.abc.trade.util.StockTraderLogger"/>
    

    @Component
    public class StockTraderLogger { /**/ }
    

    【讨论】:

      【解决方案4】:

      我觉得你不见了

      <context:annotation-config />
      

      还要确保你的 ConfigService 类有

      @Service("configService") 
      

      注解,它将使这个类成为自动装配的候选者。

      当然你应该使用

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

      为 ConfigService 包名。

      【讨论】:

      • 组件扫描存在于我的 XML 中,您可以在我共享的 XML 代码中看到它本身。我需要改变它吗?
      • 你需要更改或添加新的,它指的是configService包
      • 你可以检查 beansdefinition.xml,因为我添加了组件扫描,它指的是服务包。但输出相同。
      • 能否请您发布ConfigService代码和它的接口代码?
      • 有没有人有合适的解决方案。我也试过但没有工作。让我们尽可能关闭它..
      猜你喜欢
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多