如果我正在开发一个相对简单的基于Spring Boot的控制台应用程序,我不确定主要执行代码的位置。我应该将其放在public static void main(String[] args)
方法中还是让主应用程序类实现CommandLineRunner
接口并将代码放在run(String... args)
方法中?
我将使用一个示例作为上下文。假设我有以下[基本]应用程序(使用接口编码、Spring方式):
Application.java
public class Application {
@Autowired
private GreeterService greeterService;
public static void main(String[] args) {
// ******
// *** Where do I place the following line of code
// *** in a Spring Boot version of this application?
// ******
System.out.println(greeterService.greet(args));
}
}
GreeterService.java(接口)
public interface GreeterService {
String greet(String[] tokens);
}
GreeterServiceImpl.java(实现类)
@Service
public class GreeterServiceImpl implements GreeterService {
public String greet(String[] tokens) {
String defaultMessage = "hello world";
if (args == null || args.length == 0) {
return defaultMessage;
}
StringBuilder message = new StringBuilder();
for (String token : tokens) {
if (token == null) continue;
message.append(token).append('-');
}
return message.length() > 0 ? message.toString() : defaultMessage;
}
}
Application.java
的Spring Boot版本相当于以下内容:
GreeterServiceImpl.java(实现类)
@EnableAutoConfiguration
public class Application
// *** Should I bother to implement this interface for this simple app?
implements CommandLineRunner {
@Autowired
private GreeterService greeterService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println(greeterService.greet(args)); // here?
}
// Only if I implement the CommandLineRunner interface...
public void run(String... args) throws Exception {
System.out.println(greeterService.greet(args)); // or here?
}
}
CommandLineRunner
,它的设计目的就是这样,您还可以创建一个实例,并将依赖项注入其中。在第一个场景中,这种方法会失败,因为您无法注入依赖项或无法从静态方法中访问它。 - M. DeinumApplication
类)。这涉及到关注点分离(启动应用程序和执行逻辑的分离)。 - M. DeinumCommandLineRunner
接口可以被任何需要在Spring应用程序中运行的bean使用。我错误地认为它的目的与在命令行上运行应用程序密切相关。鉴于使用服务处理命令行参数的基本要求,开发Spring Boot应用程序的推荐方法是什么?如果是这样,那么一个Spring Boot应用程序必须有一个带有main方法的类吗?如果是这样,那么Application
将只做这些。 - Web User