【发布时间】:2021-02-09 17:33:51
【问题描述】:
所以目前,我有两个项目,比如说 Storefront 和 Dashboard,这两个项目都有相同的 POJO 类、服务和一些 API 端点。例如,考虑一个类 Student,我们在 Storefront 和 Dashboard 中都有这个类及其服务类。此外,在不久的将来,我们将为客户实施另一个项目,即客户端仪表板,它将拥有几乎 90% 的相同资源。
所以我想,如果我创建一个包含所有项目所需的所有库的 maven 项目并根据需要导入它们会怎样。这将减少冗余,也将减轻其他项目的重量。我以前使用过项目内存储库和 Dropbox 作为 maven 存储库,所以这次对我来说会更容易一些。
现在的问题是:我有 StudentRepository 对应于 Student,它进一步与 '@Autowired' 注释一起使用对吗?据我所知,当我运行“@SpringBootApplication”时,一切都会正常工作,但正如我之前提到的,我将导入这些包,并且这样做,程序将通过 NullPointerException 导致 StudentRepository 的实例为空。
@SpringBootApplication
@EnableAutoConfiguration
@EntityScan
public class DemoApplication implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
StudentRepository repository;
public static void main(String[] args) {
SpringApplication.run(PaperTrueLibrariesApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// This will work
logger.info("Inserting -> {}", repository.save(new Student("studentName", "primaryKey")));
}
// This won't
public void addAStudent(String studentName, String primaryKey) {
repository.save(new Student(studentName, primaryKey));
}
}
public class Test {
public static void main(String[] args) {
// This will throw a NullPointerException
new DemoApplication().addAStudent("yourNameProbably", "yourSocialSecurityNumber");
}
}
那么还有其他方法可以使这项工作吗?任何建议将不胜感激,并提前致谢。
【问题讨论】:
-
问题不是很清楚,我重新表述一下所以当你在另一个项目中导入这个项目时,StudentRepository会因为@Autowired而为空?
标签: java spring-boot hibernate maven jpa