I'm working on a Spring Boot web application and I'm implementing a filter (jakarta.servlet.Filter) for authentication. The filter needs some information from the database before it can authenticate the provided credentials, but I can't figure out how to get at the data because it's outside of the context of the Spring framework.
If I define a reference to a repository (org.springframework.stereotype.Repository) it doesn't get populated, it remains null. eg:
@Component
public class AuthFilter implements Filter {
private SystemPropertyReposity spr; // <-- null
@Override
public void init(FilterConfig filterConfig) throws ServletException {
SystemProperty sp = spr.findByPropertyKey(CLIENT_ID_KEY); // <-- NullPointerException because spr is null.
}
}
@Repository
public interface SystemPropertyRepository extends JpaRepository<SystemProperty, Integer>{
SystemProperty findByPropertyKey(String propertyKey);
}
I have the following set in my application.properties
:
spring.datasource.url=jdbc:postgresql://localhost:5432/mypostgresdb
spring.datasource.username=####
spring.datasource.password=####
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
Elsewhere in my application, wherever it's within a Spring framework context, I'm able to access the database without problem. It's probably something simple I've overlooked, but how am I supposed to get at my database from within my filter?
You are missing an @Autowired
on the SystemPropertyReposity spr
field or, even better a constructor