这是基于https://spring.io/guides/gs/accessing-data-jpa/
我尝试将 demo()
移动到不同包中的不同类中(Application
仍然位于文件系统层次结构的顶部)
如何让 demo()
在启动项目时运行?
应用程序.java
package com.company.app
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
CommandLineRunner.java
package com.company.app.runner
public class Test {
@Bean
public CommandLineRunner demo() {
System.out.print("Run 1");
return (args) -> {
System.out.print("Run 2");
};
}
}
最佳答案
将@Configuration
添加到Test
类中,以便在扫描类路径时拾取它。
我以前没有见过 CommandLineRunner 的 Lambda。非常漂亮,无需创建专门实现 CommandLineRunner 的类。
否则,您可以实现 CommandLineRunner 来测试并注释为 @Component。
@Component
public class ApplicationLoader implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.print("Run 2");
}
}
* 更新 * 通过此更新回答评论中的问题,因为我有更多的空间可以输入...
@SpringBootApplication
按照您的指示组成其他注释,但这些注释仅应用于定义它的特定类。 @Configuration
注释告诉 Spring 该类定义了应该由应用程序上下文管理的 bean。 @ComponentScan
告诉 spring 在类路径中查找具有特定注释的类(例如 @Component
、@Service
、@Configuration
),然后对这些类执行操作基于注释类型的类。 @EnableAutoConfiguration
是根据项目依赖项加载适当 bean 的魔法(例如,如果 mongo 驱动程序位于类路径上,则创建一个 MongoTemplate
)。
关于spring - 在 @SpringBootApplication 外部执行 CommandLineRunner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887595/