【发布时间】:2017-07-21 08:15:46
【问题描述】:
很多类似的问题,但没有一个解决方案对我有用。我有一个扩展 MondoRepository 的 Repository 接口。
public interface Repository extends MongoRepository<Subject, String> {
Subject findByName(String name);
}
这是主题类
public class Subject {
@Id
private String id;
private String name;
public String getName() {
return this.name;
}
}
上面两个文件在/db包里
如果我在我的 Application 类中自动装配 Repository,我就可以正确使用它。
@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@EnableMongoRepositories(basePackageClasses=Repository.class )
public class Application implements CommandLineRunner{
@Bean
public Service service() {
return new Service();
}
@Autowired
private Repository repository;
@Override
public void run(String... args) throws Exception {
repository.save(new Subject());
Subject subject = repository.findByName("hello");
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我的 Application 类位于根文件夹 / 中。
基本上,这不会给我任何错误。但是如果我在这样的服务类中自动装配它
public class Service {
@Autowired
private Repository repository;
public String get() {
repository.findByName("hello");
return "";
}
}
这在 repository.findByName() 行中给了我一个空指针异常。
我的 Service 课程在 /service 包中。
为什么它的行为与应用程序类中的不同? 为了能够在服务类中使用存储库,我应该做些什么不同的事情?
我尝试过的 -
我尝试用@Service, @Repository, @Component 注释我的Service 类,但它们都不起作用。
我尝试为Application 类添加注释@ComponentScan(basePackageClasses = Service.name),但没有成功。
任何解决方法也可以 -
【问题讨论】:
-
你的包是如何设置的?您的
Service类是否位于与您的Application和Repository类不同的包装结构中? -
是的,
Service类位于不同的包中。Repository和Subject类在db包中,Service在service包中,Application类在外面。 -
您可以使用
@Service注释来注释您的Service,如果Application类位于根级别包中,那么您的注释应该被拾取。 -
我试过
@Serviceannonation,它没有用。还是一样的 NullPointerException -
在
Application类中添加@ComponentScan(service package)注解
标签: mongodb spring-boot autowired mongorepository