gpt4 book ai didi

java - 为什么在这种特定情况下 Autowiring 为空?

转载 作者:行者123 更新时间:2023-12-01 21:55:46 24 4
gpt4 key购买 nike

我有一个项目,我使用注释@Autowired。我得到了一些端点、服务和存储库。除此之外,我想创建一个 javax.servlet.Filter 以在其前面放置一个过滤器。除了过滤器之外,一切正常。

我的代码是这样的:

(过滤器)

package com.mysportslife.web.auth;

<import>

@Provider
@Component
public class TokenFilter implements Filter {

@Autowired
private UserService userService;

@Autowired
private TokenService tokenService;
....
....

( token 服务)

package com.mysportslife.web.auth;
<import>

@Service
public class TokenService {

@Autowired
private UserService userService;
....
....

(用户服务)

package com.mysportslife.services;

<import>


@Service
public class UserService {

@Autowired
private UserRepository userRepository;
....
....

(web.xml)

<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>mysportslife</display-name>
<description>Backend for MySportslife</description>

<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.mysportslife.web</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>TokenFilter</filter-name>
<filter-class>com.mysportslife.web.auth.TokenFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TokenFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>

<!-- Algemene configuratie -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:ApplicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

(ApplicationContext.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:component-scan base-package="com.mysportslife"/>
<import resource="ApplicationContext-persistence.xml"/>

</beans>

有人知道为什么过滤器中的 userservice 和 tokenservice 为空吗?

如果需要更多信息,请告诉我。提前致谢!

最佳答案

这是因为该对象不是通过 Spring 初始化的。为了让 Spring Autowiring 你的 bean,你需要( super 简单版本):

  • 通过 Spring 实例化 Autowiring bean
  • 实例化您通过 Spring 连接 Bean 的bean

在您的情况下,第二个条件不满足。

这里有更详细的解释:

DelegatingFilterProxy explained

关于java - 为什么在这种特定情况下 Autowiring 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34342770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com