首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免将服务作为参数传递

如何避免将服务作为参数传递
EN

Stack Overflow用户
提问于 2021-11-10 05:32:26
回答 3查看 73关注 0票数 0

如何避免将服务作为参数传递到构造函数中?如果将其声明为一个实例,我将得到一个空值。我正在使用带有Spring Boot和Java v11的Vaadin14

代码语言:javascript
复制
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());
    }
}}
EN

回答 3

Stack Overflow用户

发布于 2021-11-10 06:55:35

您不应该手动实例化@Route类。从技术上讲,没有什么可以阻止你这样做,但这几乎肯定会让你的代码更难理解,正如你已经注意到的,你不能使用Spring依赖注入。

票数 1
EN

Stack Overflow用户

发布于 2021-11-10 08:39:46

我能够通过在我的服务类中实现一个单例来解决它。

代码语言:javascript
复制
@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();
    }
}
票数 0
EN

Stack Overflow用户

发布于 2021-11-19 12:52:18

构造函数注入和字段注入之间的区别在于,对于字段注入,在构造函数期间,注入的组件不可用(==>为空),它将直接在构造函数之后可用,例如,在使用@PostConstruct注释的方法中,或者在任何后续阶段的中,只要构造函数已经完成

代码语言:javascript
复制
// 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视图、..

在我看来,使用字段注入而不是构造函数注入并没有真正的好处。因为通常您希望注入的组件在构造函数期间可用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69908377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档