我想通过依赖注入(@Autowire)创建一个DAO对象,但不幸的是,这个DAO对象永远不会被创建,因此抛出了Nullpointer。
这是我的DAO实施:
package com.sample.dao.service;
@Component
public class OrderServiceImpl implements OrderService {
private final OrderRepository orderRepository;
@Autowired
OrderServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Override
public void save(Order order) {
return orderRepository.save(order);
}
导致Nullpointer的类:
package com.sample.dispatcher;
@Component
public class OrderDispatcher {
private final OrderServiceImpl orderServiceImpl;
@Autowired
public OrderDispatcher(OrderServiceImpl orderServiceImpl) {
this.orderServiceImpl = orderServiceImpl;
}
public void createOrder(Order order) {
orderServiceImpl.save(order)); // --> Nullpointer
我的入门课程:
package com.sample;
@SpringBootApplication
@ComponentScan(basePackages = { "com.sample" , "com.webservice"})
@EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
答案 0 :(得分:0)
我认为您应该将构造函数更改为具有参数类型的接口而不是具体实现。所以像这样 -
@Component
public class OrderDispatcher {
private final OrderService orderServiceImpl;
@Autowired
public OrderDispatcher(OrderService orderServiceImpl) {
this.orderServiceImpl = orderServiceImpl;
}
当你在OrderServiceImpl上添加@component表示法时,spring会为该类创建代理,并且它可以由接口自动装配。
答案 1 :(得分:0)
也许您忘记了@annotation配置,请尝试添加此类并扫描实体:EntityScan
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EntityScan("com.sample.model") // your model package
@ComponentScan(basePackages = { "com.sample" , "com.webservice"})
@EnableJpaRepositories(basePackages = "com.sample.dao.repository")
public class RepositoryConfig {
}