Java Autowired实例为null并导致NullPointerException
在第一种情况下,autowired cartService工作正常,但我不知道为什么在第二种情况下,当我想在另一个类中使用autowired cartService时,它的值为null。 以下是来源的一部分: 存储库:Java Autowired实例为null并导致NullPointerException,java,spring,vaadin,autowired,Java,Spring,Vaadin,Autowired,在第一种情况下,autowired cartService工作正常,但我不知道为什么在第二种情况下,当我想在另一个类中使用autowired cartService时,它的值为null。 以下是来源的一部分: 存储库: @Repository public interface CartRepository extends JpaRepository<Cart, Integer> { Cart findById(int id); } 您没有显示在Purchase类中的何处碰巧
@Repository
public interface CartRepository extends JpaRepository<Cart, Integer> {
Cart findById(int id);
}
您没有显示在Purchase类中的何处碰巧得到了NullPointerException,但我怀疑它发生在构造函数中,因为这会非常有意义 自动关联发生在对象构造之后。因此,您的autowired cartService在构造函数中为null。如果有一个方法用@PostConstruct注释,那么在自动连接之后会调用该方法-您的服务将在那里 或者您可以从字段注入切换到构造函数注入。通过使用构造函数注入,cartService将在构造函数中已经可用
@Route("purchase")
@Component
@UIScope
public class Purchase extends VerticalLayout {
// no annotation here!
CartService cartService;
//this way cartService is not null in constructor
@Autowired
public Purchase(CartService cartService){
this.cartService = cartService;
}
}
@弹簧组件?您是指@Service,它是@Component的专门化吗?——您应该从接口中删除@Service,因为@Service/@Component用于注释实现类。ColumnLay不是Springbean。这就是为什么它不会在自动连接发生的应用程序上下文中处理。当然,你是对的,我只是尝试了它,然后意外地将它保留了。我尝试了,但仍然为空,我将@Component放入ColumnLay…从CartService接口删除@Service。将@SpringComponent替换为CartServiceImpl上的@Service。应该就这些了。最初我采用了你建议的第一种方法,我也尝试了构造函数注入的第二种方法,但是这些方法都不起作用,仍然得到空值…有什么想法吗?我的假设正确吗,nullPointerException正在构造函数中发生?不,我在类中有另一个方法,两个类中都出现了我得到null的情况。
@Service
public class CartServiceImpl implements CartService{
@Autowired
CartRepository cartRepository;
@Override
public Iterable<Cart> getAllCart() {
return cartRepository.findAll();
}
@Override
public Cart getCart(int id) {
return cartRepository.findById(id);
}
@Override
public void save(Cart cart) {
cartRepository.saveAndFlush(cart);
}
}
@Component
public class ColumnLay extends VerticalLayout {
@Autowired
CartService cartService;
//...some code...cartService works fine
}
@Route("purchase")
@Component
@UIScope
public class Purchase extends VerticalLayout {
@Autowired
CartService cartService;
//here when I use cartService I get null
//some code goes here
}
@Route("purchase")
@Component
@UIScope
public class Purchase extends VerticalLayout {
// no annotation here!
CartService cartService;
//this way cartService is not null in constructor
@Autowired
public Purchase(CartService cartService){
this.cartService = cartService;
}
}