2016-10-02 184 views
1

這可能是關於使用Mongodb和Spring的一個常見問題。我沒想到會問這裏的問題,因爲每當我陷入困境時,我都可以在這裏找到解決方案。但這次沒有任何關於這個話題可以幫助我解決這個問題已經回答問題......MongoDB Spring - 沒有定義名爲'mongoTemplate'的bean

我認真不知道該怎麼辦...這裏的情況是:

這是我的應用程序上下文(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:[email protected]" /> 

<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,它在控制器中工作。你們可以看到我做錯了什麼,也許我錯過了配置中的某些東西......?

+0

嘗試改變 <背景:組件掃描base-package =「nl.company.department.project.controller.controllers」/> Veeram

+0

我改變它,但它會給我相同的錯誤之前 – Hakan54

+0

更新包qstn其中UserRepository位於.. –

回答

0

你可以試試下面請:

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

+0

我嘗試這樣做的方案,但它不會工作。我我有另一個類將會初始化Spring Security: public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { \t public securityW ebApplicationInitializer(){ \t \t超級(SecurityConfig.class); \t}} 是 – Hakan54

0

我想你應該添加@Configuration和@EnableWebSecurity註釋SecurityConfig

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
} 
+0

我忘了,一但錯誤仍然顯示... – Hakan54

相關問題