我注意到Spring Boot应用程序类可以扩展其他类,但main(String[] args)
方法通常都使用SpringApplication.run(Application.class, args)
。这些示例通常在Application
类定义之上使用不同的注释。
本OP要求简要总结三个密切相关的问题:
1。)Spring Boot Application.java类可以扩展哪些类?
2。)每个扩展选项的预期用途是什么?
3。)并且给定扩展的选择是否也规定了必须添加到类定义中的特定注释?
根据我的研究,我确定了以下三种扩展选项:
1。)根据这个例子,根本没有扩展:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2。)根据此示例扩展WebMvcConfigurerAdapter
:
@SpringBootApplication
@Controller
public class UiApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(UiApplication.class, args);
}
}
3。)根据此示例扩展SpringBootServletInitializer
:
@Configuration
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String... args) {
System.setProperty("spring.profiles.default", System.getProperty("spring.profiles.default", "dev"));
final ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
}
}
请注意,我保留了示例中的注释和最少的其他内容。该OP仅询问特定注释选择或最小其他内容是否由扩展选择决定。
答案 0 :(得分:1)
另一个不是继承而是它的组合,是实现CommandLineRunner接口,以便在Spring Boot应用程序启动时执行某些操作,如下所示:
@SpringBootApplication
public class DevopsbuddyApplication implements CommandLineRunner {
/** The application logger */
private static final Logger LOG = LoggerFactory.getLogger(DevopsbuddyApplication.class);
@Autowired
private UserService userService;
@Value("${webmaster.username}")
private String webmasterUsername;
@Value("${webmaster.password}")
private String webmasterPassword;
@Value("${webmaster.email}")
private String webmasterEmail;
public static void main(String[] args) {
SpringApplication.run(DevopsbuddyApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
User user = UserUtils.createBasicUser(webmasterUsername, webmasterEmail);
user.setPassword(webmasterPassword);
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(user, new Role(RolesEnum.ADMIN)));
LOG.debug("Creating user with username {}", user.getUsername());
userService.createUser(user, PlansEnum.PRO, userRoles);
LOG.info("User {} created", user.getUsername());
}
}
不确定这是否是您正在寻找的。 p>