[英]How to avoid passing a service as a parameter
如何避免在構造函數中將服務作為參數傳遞? 如果將它聲明為一個實例,我會得到一個空值。 我在 Spring Boot 和 Java v11 中使用 Vaadin14
public interface AccountRoleRepository extends JpaRepository<AccountRole, Long> {
}
@Service
public class AccountRoleRepositoryService {
@Autowired
private AccountRoleRepository repository;
public List<AccountRole> findAll() {
return repository.findAll();
}}
@PageTitle("User Access")
@Route(value = "user-access", layout = MainLayout.class)
public class UserAccessView extends Div {
// @Autowired
// private AccountRoleRepositoryService accountRoleRepositoryService;
public UserAccessView(AccountRoleRepositoryService accountRoleRepositoryService) {
for(AccountRole ar : accountRoleRepositoryService.findAll()){
System.out.println("role: "+ar.getRole());
}
}}
您不應手動實例化 @Route 類。 從技術上講,沒有什么可以阻止您這樣做,但這幾乎肯定會使您的代碼更難以理解,並且正如您所注意到的,您不能使用 Spring 依賴項注入。
我能夠通過在我的服務類中實現一個單例來解決它。
@Service
public class AccountRoleRepositoryService {
private static AccountRoleRepository repository;
private static AccountRoleRepositoryService INSTANCE;
private AccountRoleRepositoryService(AccountRoleRepository repository) {
this.repository = repository;
}
public synchronized static AccountRoleRepositoryService getInstance() {
if(INSTANCE == null) {
INSTANCE = new AccountRoleRepositoryService(repository);
}
return INSTANCE;
}
public List<AccountRole> findAll() {
return repository.findAll();
}
}
構造函數注入和字段注入的區別在於,使用字段注入,注入的組件在構造函數期間不可用(==> null),它將在構造函數之后直接可用,例如在用@PostConstruct
注釋的方法中@PostConstruct
或在任何稍后階段,只要構造函數已完成。
// example of Vaadin View class using field injection
@PageTitle("User Access")
@Route(value = "user-access", layout = MainLayout.class)
public class UserAccessView extends Div {
@Autowired
private AccountRoleRepositoryService accountRoleRepositoryService;
public UserAccessView() {
// accountRoleRepositoryService is null at this point
}}
@PostConstruct
public void methodThatRunsAfterConstructorCompleted() {
for(AccountRole ar : accountRoleRepositoryService.findAll()){
System.out.println("role: "+ar.getRole());
}
}
然而:
在我看來,你問這個是因為你想自己實例化你的 UserAccessView 類(-> new UserAccessView()
)。 我不知道你為什么要那樣做,但請注意,在這種情況下,任何注入都不起作用。 甚至像上面那樣的場注入。 使用@Autowired
或@Inject
注入僅在類被底層框架自動實例化時起作用 -> spring 組件、vaadin 視圖、..
在我看來,使用字段注入而不是構造函數注入沒有真正的好處。 因為通常您希望注入的組件在構造函數期間可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.