1. 程式人生 > >SpringSecurity4使用UserDetailsService時無法注入資料庫持久層的service、dao

SpringSecurity4使用UserDetailsService時無法注入資料庫持久層的service、dao

在使用SpringSecurity4時無法自動注入service層:程式碼如下:

@Service("customUserDetailsService")
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private  UserService userService;


    public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException { System.out.println("username>>>>"+username); User user = userService.findByUserName(username); System.out.println("user>>>>"+user); if (user == null ){ System.out.println("User not found"); throw
new UsernameNotFoundException("Username not found"); } return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassWord(), user.getState().equals("Activite"),true, true,true,getGrantedAuthorities(user)); } private
List<GrantedAuthority> getGrantedAuthorities(User user){ List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for(UserToProfileid userToProfileid : user.getUserToProfileidHashSet()){ System.out.println("userToProfileid : "+userToProfileid); authorities.add(new SimpleGrantedAuthority("ROLE_"+userToProfileid.getProfileid().getType())); } System.out.print("authorities :"+authorities); return authorities; } }

在執行上段程式碼是userService一直是空指標異常,後來用dao嘗試也是一樣,報錯NPE,
解決辦法:
後來查閱資料發現是因為專案的載入問題,在執行專案時,spring的載入檔案還沒有載入進來,所以導致無法,對於這種處理方式只需要在啟動專案是載入下spring的配置檔案:
只要對web.xml新增以下內容即可:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:config/spring-security.xml
      classpath:config/spring-mvc.xml   //載入spring配置檔案
    </param-value>
  </context-param>