spring @autowired注解问题,类中不注入bean,使用Spring3.0,hibernate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5950836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:29:15  来源:igfitidea点击:

@autowired annotation issue, not injecting bean in class, using Spring3.0, hibernate

hibernatespringspring-mvcannotationsspring-annotations

提问by Sagar

following is my class:

以下是我的课:

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);          
    }
}

@Autowireannotation is not working. It is displaying value of configServiceas nullwhen called addMessagemethod. however it is properly injected in some of my Controller classes but not here.

@Autowire注释不起作用。它显示的值configService作为时调用addMessage方法。但是它被正确地注入到我的一些 Controller 类中,但不是在这里。

Can anyone explain what is problem? and how to resolve this issue?

任何人都可以解释什么是问题?以及如何解决这个问题?

Code for XML is:(beansdefinition.xml)

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>

Another XML is:(Springmvc-servlet.xml)

另一个 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>

Thank you in advance.

先感谢您。

ConfigService:

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;
}

Config Service Implementor:

配置服务实现者:

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);
        }

    }

}

回答by Erhan Bagdemir

StockTraderLogger is not declared as spring bean and doesn't exist in spring context and for that reason the injection won't work.

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

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

or

或者

@Component
public class StockTraderLogger { /**/ }

回答by Prasad

Here the problem is in debug method:

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

    StockTraderLogger stl =new StockTraderLogger();

This is not spring managed. You can inject Spring managed bean into non-managed one in two ways. Here you can inject configService in StockTraderLogger as:

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

1) By AutowireCapableBeanFactory:

1) 通过 AutowireCapableBeanFactory:

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

2) By using Spring AOP @Configurable annotation which marks a class as eligible for Spring-driven configuration(like objects instantiated with the 'new' operator).

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

    @Configurable
    public class StockTraderLogger {
    ...
    }

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

You can find more information about this spring aop way here.

您可以在此处找到有关此 spring aop 方式的更多信息。

回答by Rahul

Add this to applicationContext.xml:

将此添加到applicationContext.xml

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

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

and

http://www.springframework.org/schema/mvcto xsi:schemalocation

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

mvc-annotation driven is required for annotated controllers and other features:

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

<mvc:annotation-driven />

<mvc:annotation-driven />

回答by danny.lesnik

I think you are missing

我想你失踪了

<context:annotation-config />

Also make sure that your ConfigService class has

还要确保您的 ConfigService 类具有

@Service("configService") 

Annotation, it will make this class candidate for autowiring.

注释,它将使此类成为自动装配的候选者。

and of cause you should use

因为你应该使用

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

for the ConfigService package name.

对于 ConfigService 包名称。