【问题标题】:Spring @Autowired not working in some classesSpring @Autowired 在某些类中不起作用
【发布时间】:2018-11-23 19:08:00
【问题描述】:

所以我使用 Spring 来访问我的数据库并根据不同的属性获取用户。使用@Restcontroller,我得到了数据。我创建了一个扩展 CrudRepository 的 UserRepository。

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Integer> {
Iterable<User> findByNachname(String nachname);

    Iterable<User> findByRolle(Rolle rolle);

    Optional<User> findByBenutzername(String benutzername);

    @Transactional
    String deleteByBenutzername(String benutzername);
}

我使用@Autowire 在我的控制器类中获取 UserRepo 的实例

@RestController
public class LoginController {
    @Autowired
    private UserRepository userRepository;
}

这在我拥有的所有控制器中都可以正常工作。 但是现在当我在另一个类中尝试相同的操作时,userRepository 实例为空。

public class Authentificator {
    @Autowired
    private UserRepository userRepository;
}

Authentificator 和 LoginController 不在同一个包中。但是它们都与 UserRepo 不在同一个包中。

  • 项目
    • UserRepo 包
    • 控制器包
    • 验证器包

【问题讨论】:

  • 看来 Authentificator 不是 Spring bean。是吗?你如何获得它的实例? Spring 仅自动装配 Spring bean 中的依赖项,这些依赖项必须由 Spring 创建。

标签: java spring spring-repositories


【解决方案1】:

您必须确保 Authentificator 也是一个 Spring bean - 我的意思是您必须使用 @Component 或 @Service 之类的东西对其进行注释。在这一步之后,您还必须从 spring 中“获取”Authentificator 实例,而不是使用 new 关键字来实例化它。

【讨论】:

  • 通过使用 new 实例化 Authentificator 后,它现在可以正常工作了
  • 哦,就是这样:)
【解决方案2】:

@Autowired 仅适用于 spring 上下文。这意味着它只适用于由 Spring 管理的类实例。您的 Authentificator 类由您管理,Spring 不必关心或知道它,它对 Java 框架并不重要。

这更多是配置问题,而不是注释问题。

【讨论】:

    【解决方案3】:

    如果您希望 Spring 在 Authenticator 对象中注入字段,则依赖对象也必须由 Spring 创建。您可以通过将此类标记为@Component 或创建一个带有Authenticator 返回类型的方法来标记@Beanannotation。那么它必须注入到某个地方。

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2022-08-04
      相关资源
      最近更新 更多