MongoDB Spring - 没有名为&mongoTemplate'被定义为

时间:2016-10-02 21:40:35

标签: 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> {

}

在我的控制器中,我已经自动连接了这个存储库,当我在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并且它在控制器中工作。你们能看到我做错了什么,也许我错过了配置中的一些东西......?

2 个答案:

答案 0 :(得分:0)

你可以尝试以下pls:

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

答案 1 :(得分:0)

我认为您应该将@Configuration和@EnableWebSecurity注释添加到SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}