【问题标题】:MongoDB Spring - No bean named 'mongoTemplate' is definedMongoDB Spring - 没有定义名为“mongoTemplate”的bean
【发布时间】:2016-10-02 21:40:35
【问题描述】:

这可能是关于使用 Mongodb 和 Spring 的常见问题。我没想到会在这里问问题,因为每次遇到困难时,我都可以在这里找到解决方案。但是这一次,关于这个主题的已经回答的问题都不能帮助我解决问题......

我真的不知道该怎么办......情况如下:

这是我的应用程序上下文(ONE-servletConfig.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<mvc:annotation-driven />

<context:annotation-config/>
<context:component-scan base-package="nl.company.department.project.controller.controllers,nl.company.department.project.mongodb"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property value="WEB-INF/jsp/" name="prefix" />
    <property value=".jsp" name="suffix" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />


<mongo:mongo-client id="mongo" host="abcdefgh.mlab.com"
    port="123456" credentials="apple:pie@appledb" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongo" ref="mongo" />
    <constructor-arg name="databaseName" value="opadb" />
</bean>

<bean
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer" />

<mongo:repositories base-package="nl.company.department.project.mongodb"
    mongo-template-ref="mongoTemplate" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="100000" />
</bean>

我的 web.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<web-app 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" version="3.0">
<display-name>ONE</display-name>

<servlet>
    <servlet-name>ONEapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/ONE-servletConfig.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>ONEapp</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

我的存储库在 nl.company.department.project.mongodb 包中 存储库之一:

@Repository
public interface UserRepository extends MongoRepository<User, String> {

}

在我的控制器中,我已经自动连接了这个存储库,当我在 userCollection 上使用方法时,它将工作并返回数据库的值。这是控制器:

@RestController
@RequestMapping("consultants")
public class OPAController {

    @Autowired
    private UserRepository userCollection;

    more code ...
}

用户对象如下所示:

@Document(collection="user")
public class User {
    @Id
    @Getter @Setter private String name;
    @Getter @Setter private String password;
}

我想使用 Spring Security,所以我创建了几个类...

安全配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/consultants/sendPassword","/consultants/authenticateUser")
            .permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .csrf().disable();
    }
}

还有 SecurityWebApplicationInitializer 类:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
    super(SecurityConfig.class);
    }
}

还有 CustomAuthenticationProvider 类

@Component
@EnableMongoRepositories(basePackages = "nl.company.department.project.mongodb")
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserRepository userCollection;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (userCollection.findOne(name) != null && userCollection.findOne(name).getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

所以在控制器中自动装配存储库是可行的,但是当我想在 CustomAuthenticationProvider 类中使用存储库时,它会抛出以下异常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'userCollection': Error creating bean with name 'userRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined

但奇怪的是我确实定义了 mongoTemplate 并且它在控制器中工作。你们能看到我做错了什么吗,也许我在配置中遗漏了一些东西......?

【问题讨论】:

  • 尝试更改
  • 我改变了它,但它会给我和以前一样的错误
  • 用 UserRepository 所在的包更新 qstn..
  • 是的,我添加了 UserRepository 的包

标签: java spring mongodb spring-mvc


【解决方案1】:

你可以试试下面吗:

<mongo:db-factory dbname="mongoDb" host="mongoServer" port="mongoPort"/>


<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.basePackage"/>

【讨论】:

  • 我试过了,但它不起作用。我的想法是 springfilter 导致了这个问题。我有另一个将初始化 Spring Security 的类: public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { public SecurityWebApplicationInitializer() { super(SecurityConfig.class); } }
【解决方案2】:

我认为你应该在 SecurityConfig 中添加 @Configuration 和 @EnableWebSecurity 注解

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2017-01-10
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多