java - MongoDB Spring - 未定义名为 'mongoTemplate' 的 bean

标签 java spring mongodb spring-mvc

这可能是有关使用 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> {

}

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

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

因此,在 Controller 中 Autowiring 存储库是可行的,但是当我想在 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 并且它在 Controller 中工作。你们能看到我做错了什么吗,也许我错过了配置中的某些内容......?

最佳答案

您可以尝试以下操作吗:

<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"/>

关于java - MongoDB Spring - 未定义名为 'mongoTemplate' 的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821976/

相关文章:

java - 如何将软键盘隐藏在 fragment 中?

java - 在应用程序中存储 ip 地址的最佳方法是什么?

xml - 强制 JacksonXML 将原始 XML 反序列化为字符串

c# - 带有 MongoDb 的 ASP.NET Core 3.1 中的身份服务器 4

java - 类不是抽象的,不会覆盖抽象方法

java - Apache POI XSSF 从 RGB 设置 fillForegroundColor

java - 无法在intellij中将Spring mvc部署到tomcat

node.js - 如何通过过滤器获取所有集合名称?

node.js - MongoDB 查询将一个记录值与另一记录值相减

java - Spring 3 MVC - View 未解决