Struts2& Spring错误:没有为依赖项找到类型的限定bean

时间:2013-07-01 17:31:49

标签: spring struts2 dependency-injection spring-annotations

我的项目使用Spring 3.2和Struts2(都使用注释)。我正在通过Java配置Spring。当我尝试将一个服务注入一个动作时,我从Struts2得到以下错误:

  
      
  1. 找不到[com.ceiwc.mvc.service.IUserService]类型的限定bean用于依赖:预期至少有1个bean符合条件   autowire候选人这种依赖。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

  2.   
  3. 无法自动装配字段:private com.ceiwc.mvc.service.IUserService   com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

  4.   
  5. 使用名称' com.ceiwc.mvc.action.LoginAction'创建bean时出错:注册自动连接的依赖项失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private com.ceiwc.mvc.service.IUserService   com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

  6.   
  7. 无法实例化针对' login'定义的Action,com.ceiwc.mvc.action.LoginAction。在命名空间' /登录'使用名称创建bean时出错   ' com.ceiwc.mvc.action.LoginAction&#39 ;:注入自动装配   依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private com.ceiwc.mvc.service.IUserService   com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

  8.   

这是Stacktrace:

  

无法实例化Action,com.ceiwc.mvc.action.LoginAction,   为登录'定义在命名空间' /登录'使用名称创建bean时出错   ' com.ceiwc.mvc.action.LoginAction&#39 ;:注入自动装配   依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private com.ceiwc.mvc.service.IUserService   com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:316)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:536)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.ceiwc.mvc.action.LoginAction': Injection
     

自动连接的依赖项失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private com.ceiwc.mvc.service.IUserService   com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:203)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:183)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:154)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:121)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:536)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
 org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ceiwc.mvc.service.IUserService
     

com.ceiwc.mvc.action.LoginAction.userService;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   找到[com.ceiwc.mvc.service.IUserService]类型的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:203)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:183)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:154)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:121)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:536)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ceiwc.mvc.service.IUserService] found
     

for dependency:预计至少有1个bean可以作为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:203)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:183)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:154)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:121)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:536)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
weblogic.work.ExecuteThread.run(ExecuteThread.java:178)

以下是Spring的Java配置:

@Configuration
@ImportResource({ "/WEB-INF/spring/spring-config.xml" })
@ComponentScan(basePackages = "com.ceiwc")
public class ApplicationConfig {

}

@Configuration
@EnableTransactionManagement
@Import(ApplicationConfig.class)
@PropertySource({ "classpath:db.properties" })
public class DataConfig {

    @Autowired
    Environment environment;

    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("db.driver"));
        dataSource.setUrl(environment.getProperty("db.url"));
        dataSource.setUsername(environment.getProperty("db.username"));
        dataSource.setPassword(environment.getProperty("db.password"));
        return dataSource;
    }

    @Bean
    public JpaVendorAdapter vendorAdapter() {
        EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.ORACLE);
        vendorAdapter.setShowSql(true);
        return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] { environment
                .getProperty("db.packagesToScan") });
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter());

        return entityManagerFactoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactoryBean()
                .getObject());
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

这是我的DAO:

public interface IUserDao extends IGenericDao<User> {
    public User findUserByUsernameAndPassword(String username, String password);
}

@Repository("userDAO")
@Transactional(readOnly = true)
public class UserDaoImpl extends GenericDaoImpl<User> implements IUserDao {

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {

        Query query = getEntityManager()
                .createNativeQuery(
                        "Select u From User Where username = :username And password = :password");
        query.setParameter("username", username);
        query.setParameter("password", password);

        return (User) query.getSingleResult();
    }
}

这是我的服务:

public interface IUserService {
    public User validateUser(String username, String password);
}

@Service("userService")   
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Override
    public User validateUser(String username, String password) {
        return userDao.findUserByUsernameAndPassword(username, password);
    }

}

这是我的行动:

@SuppressWarnings("serial")
@Namespace("/Login")
@Component
public class LoginAction extends ActionSupport {

    private User user;
    private String updateFlag;

    @Autowired
    private IUserService userService;

    @Action(value = "login", results = { @Result(name = "success", location = "/pages/login/login.jsp") })
    public String login() {
        updateFlag = "Y";
        return SUCCESS;
    }

    @Action(value = "validate", results = {
            @Result(name = "success", location = "/pages/menu/index.jsp"),
            @Result(name = "login", location = "/pages/login/login.jsp") })
    public String validateUser() {
        if (updateFlag == null) {
            return LOGIN;
        }

        if (userService.validateUser(user.getUsername(), user.getPassword()) == null) {
            addActionError("You are an invalid user");
            return LOGIN;
        }

        // TODO: Add session aware info
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getUpdateFlag() {
        return updateFlag;
    }

    public void setUpdateFlag(String updateFlag) {
        this.updateFlag = updateFlag;
    }

    public IUserService getUserService() {
        return userService;
    }

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

}

这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>menuAdministration</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Helps with wiring the application together -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Needed to manage the Java based @Configuration classes for Spring -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
         org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.ceic.config</param-value>
    </context-param>

    <!-- Handles Strut2 URL requests -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

我错过了什么?我有@ Component,@ Service和@Repository构造型。所以,我不明白为什么Spring无法找到注射用的豆子。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我找到了两个解决这个问题的方法。

  1. 由于我在Spring中使用Java配置,因此必须确保我的contextConfigLocation设置正确。
  2. 我使用的jar文件包含带有Spring构造型的bean,所以我必须确保在eclipse中正确构建了jar文件。构建jar文件时,我必须确保选中了Add Directory条目选项。
  3. 这两个步骤解决了这个问题。

    我希望这有帮助!