如何从 jakarta servlet Filter 访问数据库?

问题描述 投票:0回答:1

我正在开发一个 Spring Boot Web 应用程序,我正在实施一个过滤器 (jakarta.servlet.Filter) 以进行身份验证。过滤器在验证提供的凭据之前需要数据库中的一些信息,但我无法弄清楚如何获取数据,因为它不在 Spring 框架的上下文中。

如果我定义对存储库 (org.springframework.stereotype.Repository) 的引用,它不会被填充,它仍然为空。例如:

@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);
}

我的

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

在我的应用程序的其他地方,无论它在 Spring 框架上下文中,我都能够毫无问题地访问数据库。这可能是我忽略的一些简单的事情,但我应该如何从我的过滤器中获取我的数据库?

java spring-boot hibernate jakarta-ee servlet-filters
1个回答
0
投票

你在场上缺少一个@Autowired 或(更好)一个构造函数

© www.soinside.com 2019 - 2024. All rights reserved.