2015-05-28 36 views
0

我需要讀取UserDetailsDaoImpl中的屬性值。我正在使用Spring Security。Spring MVC在DAOImpl中讀取屬性文件null

它成功讀取@Controller的內部,但不在此類中,可能是因爲它是@Repository

我該怎麼做才能讀取屬性值?

UserDetailsDaoImpl:

@Repository 
public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao { 

    @Value("${emails_blocked}") 
    private String emails_blocked; 

豆類:

<context:property-placeholder location="classpath:config.properties"/> 

編輯:

這是我如何調用UserDetailsDaoImpl:

@Autowired 
UserDetailsDao userDetailsDao; 

@Override 
public Authentication authenticate(Authentication authentication) throws AuthenticationException { 

    try { 

     Authentication auth = super.authenticate(authentication); 

     // if reach here, means login success, else exception will be thrown 
     // reset the user_attempts 
     userDetailsDao.resetFailAttempts(authentication.getName()); 

     return auth; 

    } catch (BadCredentialsException e) { 

     userDetailsDao.updateFailAttempts(authentication.getName()); 
     throw e; 

    } 

我的豆子更新:

<beans:bean id="userDetailsDao" class="com.setelog.spring.dao.UserDetailsDaoImpl" > 
    <beans:property name="dataSource" ref="dataSource" /> 
</beans:bean> 

<beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> 


<beans:bean id="authenticationProvider" 
    class="com.setelog.spring.handler.LimitLoginAuthenticationProvider"> 
    <beans:property name="userDetailsService" ref="customUserDetailsService" /> 
    <beans:property name="userDetailsDao" ref="userDetailsDao" /> 
    <beans:property name="passwordEncoder" ref="encoder" /> 

</beans:bean> 
+1

確保你沒有自己創建一個新的實例,你也有一個在<@ Repository>所在的上下文中的'如果不是什麼都將被替換。 –

+0

@ M.Deinum你能給我舉個例子嗎?我不明白。謝謝 – Kunal

+0

你不明白什麼?檢查yu使用這個控制器的地方,你不是自己創建一個新的實例,並且確保你已經在應用上下文中配置了佔位符,這個存儲庫被定義/加載進去了。 –

回答

-1

我的問題是,由於我打電話的方法就不會加載@Value,所以我不得不注入一些豆子。 像這樣:

<bean 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="locations"> 
      <list> 
       <value>classpath:config.properties</value>    
      </list> 
     </property> 
    </bean> 

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
     <property name="staticMethod" value="com.setelog.spring.dao.UserDetailsDaoImpl.setEmails_Blocked"/> 
     <property name="arguments"> 
      <list> 
       <value>${emails_blocked}</value> 
      </list> 
     </property> 
    </bean> 

我UserDetailsDaoImpl:

static String emails_blocked; 

public static void setEmails_Blocked(String emails_blocked){ 
    UserDetailsDaoImpl.emails_blocked= emails_blocked; 
} 

這個答案對我幫助很大: https://stackoverflow.com/a/24649692/4790786

+0

不,你只需要在正確的上下文中指定'''。它只會在同一個上下文中對bean進行操作,在你的情況下,只有'DispatcherServlet'加載的bean,將該行添加到'ContextLoaderListener'中。 –