我正在尝试获得一个干净的trying启动maven多模块项目。我用的是springboot 2.0.1。
我想要达到的目标类似于这样:SpringBootMultipleMavenModules
我的问题是,我希望能够在任何模块中注入我的依赖项。
例如,在这个类中:DBSeeder.java如下所示:
private HotelRepository hotelRepository;
public DbSeeder(HotelRepository hotelRepository){
this.hotelRepository = hotelRepository;
}
..我想用的是:
@Autowired
private HotelRepository hotelRepository;Application类如下所示:
@SpringBootApplication
@EnableJpaRepositories(basePackages = {"rc"})
@EntityScan(basePackages = {"rc"})
@ComponentScan(basePackages = {"rc"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}任何能将我与解决方案联系起来的想法都会受到欢迎。
发布于 2018-04-26 14:59:47
查看您的代码,您不能Autowire一个Hotel bean,因为它没有正确注册。
您需要在那里添加@Component才能将它注入到https://github.com/IDCS1426/SpringBootMultipleMavenModules/blob/master/persistence/src/main/java/rc/persistence/DbSeeder.java#L21中
此外,项目将永远不会编译,因为您正在添加一个不存在的模块:https://github.com/IDCS1426/SpringBootMultipleMavenModules/blob/master/pom.xml#L14。您需要删除它:)。
说了这些之后,我觉得你像这样注射Entity的方式很奇怪,但这不是这个问题的一部分。
通过这样做,代码就会编译得很好。
发布于 2018-04-30 08:46:10
工作解决方案是可用的这里。@Component在实体中失踪了。显然,bean不应该像这里那样注入,而是实例化(例如marriot = new Hotel("Marriot", 5, true);)并通过save方法(或集合的saveAll )持久化。
为初始化的唯一目的而注入实体是错误的,也是行不通的:每个Hotel都将重复使用相同的实例。
@Autowired
private Hotel marriot, ibis, goldenTulip;
@Override
public void run(String... strings) throws Exception {
marriot.setName("Marriot");
marriot.setClassification(5);
marriot.setOpen(true);
ibis.setName("Ibis");
ibis.setClassification(3);
ibis.setOpen(false);
goldenTulip.setName("Golden Tulip");
goldenTulip.setClassification(4);
goldenTulip.setOpen(true);
List<Hotel> hotels = new ArrayList<>();
hotels.add(marriot);
hotels.add(ibis);
hotels.add(goldenTulip);
this.hotelRepository.saveAll(hotels);
}将导致一个实体持久化,因为所有3家酒店都是相同的实例。因此,http://localhost:8080/hotels将返回:
[{"id":1,"name":"Golden Tulip","classification":4,"open":true}]当它实例化时,
@Override
public void run(String... strings) throws Exception {
marriot = new Hotel("Marriot", 5, true);
ibis = new Hotel("Ibis", 3, false);
goldenTulip = new Hotel("Golden Tulip", 4, true);
List<Hotel> hotels = new ArrayList<>();
hotels.add(marriot);
hotels.add(ibis);
hotels.add(goldenTulip);
this.hotelRepository.saveAll(hotels);
}它将与以下三个实体一样返回:
[{"id":1,"name":"Marriot","classification":5,"open":true},{"id":2,"name":"Ibis","classification":3,"open":false},{"id":3,"name":"Golden Tulip","classification":4,"open":true}]这正是我想在这里看到的,但忘记了在实体类中添加@Component。千万别这么做!
编辑:尝试的原因是使用了服务层:
public interface NoteService {
List<Note> loadAll();
}@Service
public class NoteServiceImpl implements NoteService {
@Autowired
private NoteRepository noteRepository;
@Override
public List<Note> loadAll() {
return noteRepository.findAll();
}
}结果在运行时失败了,Note不是托管bean。
https://stackoverflow.com/questions/50044126
复制相似问题