簡體   English   中英

Spring @Autowired在某些課程中不起作用

[英]Spring @Autowired not working in some classes

所以我正在使用Spring訪問我的數據庫並基於不同的屬性獲取用戶。 使用@Restcontroller可以獲取數據。 我創建了一個UserRepository,它擴展了CrudRepository。

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 Instance為null。

public class Authentificator {
    @Autowired
    private UserRepository userRepository;
}

Authentificator和LoginController不在同一程序包中。 但是,它們和UserRepo不在同一個程序包中。

  • 項目
    • UserRepo包
    • 控制器 - 包裝
    • Authentificator,包

您必須確保Authentificator也是一個spring bean-我的意思是,您必須使用@Component或@Service之類的內容對其進行注釋。 完成此步驟后,您還必須從spring中“獲取” Authentificator實例,而不是使用new關鍵字實例化它。

@Autowired確實僅在spring上下文中有效。 這意味着它僅適用於由Spring管理的類實例。 您的Authentificator類由您管理,Spring不必照顧或了解它,這對於Java Framework而言並不重要。

這更多是配置問題,而不是注釋問題。

如果您想讓Spring在Authenticator對象中注入一個字段,則依賴對象也必須由Spring創建。 您可以通過將此類標記為@Component或通過使用Authenticator返回類型標記有@Bean注釋的方法來創建@Bean 然后必須將其注入某個位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM