@Autowire在春季启动失败

时间:2017-08-31 13:00:08

标签: java spring spring-boot

我正在尝试在Spring启动应用程序中自动装配一个类。但Spring没有给出任何实例,它给出了null。

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

public JWTAuthorizationFilter( AuthenticationManager authManager )
{
    super(authManager);
}

@Autowired
private JWTUtil jwtUtil;
@Override
protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain )
        throws IOException, ServletException
{
    String jwt = req.getHeader(SecurityConstants.HEADER_STRING);

    if( jwt == null || !jwt.startsWith(SecurityConstants.TOKEN_PREFIX)  )
    {
        chain.doFilter(req, res);
        return;
    }
    if(!jwtUtil.validateToken(jwt))
    {
        chain.doFilter(req, res);
        return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(req, res);
}
}

JWTUtil jwtUtil获得空值。我已将JWTUtil.java标记为@Component注释,但仍然无效。

@Component
public class JWTUtil {

private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);
@Autowired
private  UserModelRepository userModelRepository;

public  Boolean validateToken( String jwt )
{
    Claims claims = Jwts.parser().setSigningKey(SecurityConstants.SECRET)
            .parseClaimsJws(jwt.replace(SecurityConstants.TOKEN_PREFIX, "")).getBody();

    Date createdAt = claims.getIssuedAt();
    String mobileNumber = claims.getSubject();

    Optional<UserModel> userModelOptional = userModelRepository.findByMobileNumberAndIsActiveTrue(mobileNumber);
    if( !userModelOptional.isPresent() )
    {
        return false;
    }
    UserModel userModel = userModelOptional.get();
    Calendar logoutTime = userModel.getLogoutTime();
    if( null != logoutTime )
    {
        Date logoutDate = logoutTime.getTime();
        if( logoutDate.before(createdAt) ) // new token
        {
            return true;
        }
    }
    logger.info("Invalid token....issued before last logout");
    return false;

}
}

这里也是

@Autowired private UserModelRepository userModelRepository;

变为空。为什么会这样?

修改 主要课程

@SpringBootApplication
@EnableAutoConfiguration
@EntityScan( "com.highpeak.gbi.datastore.model" )
@EnableJpaRepositories( "com.highpeak.gbi.datastore.repository" )
@ComponentScan( { "com.highpeak.gbi.webservices",     "com.highpeak.gbi.datastore" } )
public class Application {

public static void main( String[] args )
{

    SpringApplication.run(Application.class, args);
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}

}

0 个答案:

没有答案