gpt4 book ai didi

java - 多层 Spring 应用程序依赖解析

转载 作者:行者123 更新时间:2023-12-01 09:51:27 25 4
gpt4 key购买 nike

我正在尝试使用Spring创建一个三层应用程序,viewlogicdata,或多或少。 View 取决于逻辑,而逻辑又取决于数据

如何在 view 项目中配置 Spring 应用程序,以便能够解析依赖关系图?

例如:

View 层中:

@Controller
public class SomeView {
private final SomeService someService;

@Autowired
public SomeView(SomeService someService) {
this.someService = someService;
}
}

@Configuration
@EnableAutoConfiguration
@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

逻辑层:

@Component
public class SomeService {

private final SomeData someData;

@Autowired
public SomeService(SomeData someData){
this.someData = someData;
}

}

数据层:

@Component
public class SomeData {

}

此配置无法启动,因为SomeService无法解析SomeData,因为SomeData未在 View 中扫描Application.java

最佳答案

当使用@SpringBootApplication时 Spring boot 使用默认值。如果你看一下@SpringBootApplication定义你会看到:

Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes: [...]

这意味着:

@SpringBootApplication // same as @Configuration    @EnableAutoConfiguration @ComponentScan
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

此外,这意味着当使用 @ComponentScan 的默认值时,您的包结构应如下所示:

  • com.example.model -> 您的实体
  • com.example.repositoriy -> 您的存储库
  • com.example.controller -> Controller
  • com.example -> MainApplication 类

如果不遵循此结构,您应该告诉 @ComponentScan 包在哪里可以找到组件:

示例 1:

@Configuration
@EnableAutoConfiguration
@ComponentScan({"com.my.package.controller","com.my.package.domain"})
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

示例 2:

    @Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = {SomeService.class, SomeData.class})
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

另外,我建议您检查一下这个guide关于如何在 Spring Boot 应用程序中构建代码。

关于java - 多层 Spring 应用程序依赖解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com