如何避免将服务作为参数传递到构造函数中?如果将其声明为一个实例,我将得到一个空值。我正在使用带有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());
}
}}发布于 2021-11-10 06:55:35
您不应该手动实例化@Route类。从技术上讲,没有什么可以阻止你这样做,但这几乎肯定会让你的代码更难理解,正如你已经注意到的,你不能使用Spring依赖注入。
发布于 2021-11-10 08:39:46
我能够通过在我的服务类中实现一个单例来解决它。
@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();
}
}发布于 2021-11-19 12:52:18
构造函数注入和字段注入之间的区别在于,对于字段注入,在构造函数期间,注入的组件不可用(==>为空),它将直接在构造函数之后可用,例如,在使用@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视图、..
在我看来,使用字段注入而不是构造函数注入并没有真正的好处。因为通常您希望注入的组件在构造函数期间可用。
https://stackoverflow.com/questions/69908377
复制相似问题